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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With