Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 dictonary lookup using a variable key

Tags:

python

jinja2

Using Jinja2 how can I lookup the value in a dictionary where the key is a variable from a Jinja2 for loop.

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

{% for field in fields %}
<td> {{ item[field] }} </td>
{% endfor %}
like image 571
pyCthon Avatar asked Nov 30 '14 00:11

pyCthon


1 Answers

For Django, yes, this is a problem, but not for jinja2. The code you've 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>
like image 75
alecxe Avatar answered Oct 04 '22 17:10

alecxe