Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

range in jinja2 inside a for loop

I have a nested list. I need to iterate through a list and keep it in for loop as shown below.

{% for alpha in list %}
    <div id="{{ loop.index }}"> 
       <div class='sidebar-one'>
          {% for beta in list[0][2:] %} #I want to iterate through list[0][2:] till list[n][2:]
              <p> {{ beta[0][0] }} </p>
          {% endfor %}
       </div>
    </div>
{% endfor %}

I tried range but no luck.

{% for n in range(1,n) %}
{% for line in check[{{n}}][2:] %}
{% endfor %}

it threw error:

    TemplateSyntaxError: expected token ':', got '}'
like image 691
Chandan Gupta Avatar asked Jul 17 '13 05:07

Chandan Gupta


People also ask

Can we use range in for loop?

We can use a range() to simplify writing a for loop. The stop value of the range() must be specified, but we can also modify the start ing value and the step between integers in the range() .

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.

How do you iterate through a list in Jinja?

To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.


2 Answers

It's just like Python:

{% for n in range(n) %}
    {% for line in check[n][2:] %}
        <p> {{ beta[0][0] }} </p>
    {% endfor %}
{% endfor %}
like image 52
Blender Avatar answered Sep 23 '22 12:09

Blender


You can use the "length" property:

{% for n in range(yourList| length) %}
       <p class="someclass">{{n + 1}}.</p>
       <a class="someclass2" 
       href="{{ url_for( 'yourFunction', Int = yourList[n].iterable)}}">
       {{yourList[n].iterable}}</a><br>
{% endfor %}

Length is similar to len(yourlist) that we have in python.

like image 30
Dinidiniz Avatar answered Sep 24 '22 12:09

Dinidiniz