Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you index on a jinja template?

Tags:

python

jinja2

I'm passing 3 lists to my jinja template through my python file.

list1 = [1,2,3,4] list2 = ['a','b','c','d'] list3 = [5,6,7,8] 

All these values correspond with eachother, so 1 matches with 'a' and 5, 2 with 'b' and 6, etc.

In my template I'm printing them out on the same line. How do I do numerical indexing to print them out? As so

1 a 5 2 b 6 3 c 7 

The only thing I know is directly accessing the object through the loop like

 {%for item in list%}     {{item}} 
like image 723
user986173 Avatar asked Nov 27 '13 04:11

user986173


People also ask

How are variables in Jinja2 templates specified?

A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine. A template contains variables and/or expressions, which get replaced with values when a template is rendered; and tags, which control the logic of the template.

What is block content in Jinja?

All the block tag does is tell the template engine that a child template may override those placeholders in the template. In your example, the base template (header. html) has a default value for the content block, which is everything inside that block. By setting a value in home.


Video Answer


2 Answers

If you really want the index, you could just loop on one of the variables and then uses Jinja's loop.index0 feature (returns the current index of the loop starting at 0 (loop.index does the same thing, starting at 1)

For example:

{% for item in list1 %}      {{ item }}     {{ list2[loop.index0] }}     {{ list3[loop.index0] }}  {% endfor %} 

This assumes your lists are all asserted to be the same length before setting the template, or you'll encounter problems.

like image 197
Quentin Donnellan Avatar answered Oct 06 '22 00:10

Quentin Donnellan


Two ways:

  1. In your code that calls Jinja simply zip your lists:

    data = zip(list1, list2, list3) # data is now a list of tuples # [(1, 'a', 5), (2, 'b', 6), etc.] 

    Then, in your template you can simply loop over the nested rows:

    {# your_template.jinja #} <table> {% for row in data %}     <tr>     {% for cell in row %}         <td>{{ cell }}</td>     {% endfor %}     </tr> {% endfor %} </table> 
  2. As an alternate, if you only want to use Jinja you can use the special loop variable:

    <table> {% for cell in list1 %}     <tr>         <td>{{ list1[loop.index0] }}</td>         <td>{{ list2[loop.index0] }}</td>         <td>{{ list3[loop.index0] }}</td>     </tr> {% endfor %} </table> 
like image 25
Sean Vieira Avatar answered Oct 05 '22 23:10

Sean Vieira