0

how can i do this in jinja condition

My goal is to check the value of value_index every index of the loop if the next index value is same then it will not print . until the next value is not equal to value_index it will print it.

sample data:

users = [ ('username1','password1'),('username2','password1') ]
contacts  = [('0909','0909','0011','0011','0011','0908')]

so far i have this code but its not working as i expected

{% for items in users %}
  {% set i = loop %}
  {% set value_index = '' %}
  {% print(items[0]) %}

  {% for item in contacts %} 
     {% if value_index  != item  %}
        {% print(item) %}  
    {% endif %} 
    {% set value_index = item %}

  {% endfor %} 
{% endfor %} 

My expected output is

username1
0909
0011
0908
username2
0909
0011
0908

1 Answer 1

1

I suppose you're looking for loop.changed(*val) method: https://jinja.palletsprojects.com/en/2.10.x/templates/#for (see table). So, you just need to call the method in your if tag like this:

{% for items in users %}
  {% print(items[0]) %}

  {% for item in contacts %}
     {% if loop.changed(item)  %}
        {{ item }}
     {% endif %} 
  {% endfor %} 
{% endfor %} 

If the value of item actually changed from the previous call of loop.changed the result of the call is true. false otherwise.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! @sergei sadovnikov THANK YOU! :) :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.