Tuesday 15 January 2013

python - In Django template for mark next n elements -



python - In Django template for mark next n elements -

i'm trying figure out how mark next n elements in list when special element encountered.

i have info construction looks this

[ {"type": "normal1", "text": "some text 1"}, {"type": "special", "text": "some text 2", "length": 2}, {"type": "normal1", "text": "some text 3"}, {"type": "header", "text": "some text 4"}, {"type": "header", "text": "some text 5"}, ]

where types intermingled , length parameter arbitrary each special element. length parameter means special node "owns" next n elements. difference in formatting each normal type in non-trivial. want output this

<p class="normal1">some text 1</p> <div class="special"> <h1>some text2</h1> <p class="normal1">some text 3</p> <h2 class="header">some text 4</h2> </div> <h2 class="header">some text 5</h2>

i can't figure out how divs in there. far template looks this

{% line in line_list %} {% if line.type == "special" %} <h1>{{ line.text }}</h1> {% elif line.type == "header" %} <h2 class="{{ line.type }}">{{ line.text }}</h2> {% else %} <p class="{{ line.type }}">{{ line.text }}</p> {% endif %} {% endfor %}

i can alter info construction if need be, special element contains list normal elements owns, i'd either have duplicate code dealing different elements or recursive templates - i've read big no-no.

to solve problem , on ended defying advice i'd read , utilize recursive templates modified info structure. there several performance hits when doing way. doesn't matter much particular application. i'll outline below ended with.

new info structure

[ {"type": "normal1", "text": "some text 1"}, {"type": "special", "text": "some text 2", "nodes": [ {"type": "normal1", "text": "some text 3"}, {"type": "header", "text": "some text 4"} ]}, {"type": "header", "text": "some text 5"} ]

base_template

{% template_name="sub_template" %} {% include template_name %} {% endwith %}

sub_template

{% line in line_list %} {% if line.type == "special" %} <div class="{{ line.type }}"> <h1>{{ line.text }}</h1> {% line_list=line.nodes %} {% include template_name %} {% endwith %} </div> {% elif line.type == "header" %} <h2 class="{{ line.type }}">{{ line.text }}</h2> {% else %} <p class="{{ line.type }}">{{ line.text }}</p> {% endif %} {% endfor %}

python django templates

No comments:

Post a Comment