Jinja2 hint using variable key

Using Jinja2how I can find the value in the dictionary, where the key is a variable from the Jinja2for loop .

Here is an example of what I'm trying to do

{% for field in fields %}
<td> {{ item[field] }} </td>
{% endfor %}
+4
source share
1 answer

For Django, yes, this is a problem , but not for jinja2. The code you provided works:

>>> import jinja2
>>> env = jinja2.Environment()
>>> t = env.from_string("""
... {% for field in fields %}
... <td> {{ item[field] }} </td>
... {% endfor %}""")
>>> print t.generate(item={'key':'value'}, fields=['key']).next()
<td> value </td>
+5
source

All Articles