Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja2 iterate through list of tuples

Tags:

python

jinja2

I have a list of tuples called items:

[ (1,2), (3,4), (5,6), (7,8) ]

I thought I could iterate though using, but it's not working:

# Code
output = template.render( items )

# Template
{% for item in items %}
    {{ item[0] }};
    {{ item[1] }};
{% endfor %}

Any suggestions?

like image 276
Ethan Avatar asked Sep 16 '16 03:09

Ethan


People also ask

How do you iterate through a tuple list?

Use the enumerate() function to iterate over a list of tuples, e.g. for index, tup in enumerate(my_list): . The enumerate function returns an object that contains tuples where the first item is the index, and the second is the value.


1 Answers

From the documentation:

render([context])

This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty.

from jinja2 import Environment

TEMPLATE = """ 
{% for item in items %}
    {{ item[0] }};
    {{ item[1] }};
{% endfor %}
"""

template = Environment().from_string(TEMPLATE)

items = [(1,2), (3,4), (5,6), (7,8)]

print(template.render(items=items))

While parsing the template, jinja2 will look for a key called 'items' but in your case, there is none, you have to explicitly specify it.

like image 143
Nehal J Wani Avatar answered Sep 30 '22 21:09

Nehal J Wani