ibrewster
ibrewster

Reputation: 3612

jinja2: track previous value in for loop

in a jinja2 for loop, how can I keep track of what the previous value of a variable was (for purposes of displaying breaks between "groups")? The obvious and straight-forward answer of:

{% set last_val='unk' %}
{% for object in data %}
    {% if object[0]!=last_val %}
        <output whatever separation code>
        {% set last_val=object[0] %}
    {% endif %}
    <other stuff>
{% endfor %}

...doesn't work due to jinja2's scoping rules - each new time through the loop sees the same 'unk'. How can I work around this limitation?

EDIT: I was poking around some older code of mine where I had done similar things, and apparently this DID work with jinja2 2.8, but broke sometime before 2.9.6. So I guess one solution would be to downgrade to 2.8 and just stay there.

Upvotes: 7

Views: 4029

Answers (2)

Ben L
Ben L

Reputation: 355

Use "loop.previtem" .


{% for object in data %}
    {% if loop.index0 ==0  %}
        <output whatever separation code>
        
    {% elif loop.index0 > 0 and loop.previtem[0] != object[0]  %}
        <output whatever separation code>
        
    {% endif %}
    <other stuff>
{% endfor %}

Upvotes: 6

Prathamesh Patkar
Prathamesh Patkar

Reputation: 1

jinja is not able to change the value of variable ,but you can use dictionary to change value of key . this will work .

  {% set last_val={'key':'unk'} %}
  {% for object in data %}

     {% if object[0]!=last_val.key %}
        <output whatever separation code>
        {% set test = last_val.update({'unk':object[0]}) %}

     {% endif %}
     <other stuff>
  {% endfor %}

Upvotes: 0

Related Questions