How to get values from dictionary in jinja when key is a variable? How to get values from dictionary in jinja when key is a variable? python python

How to get values from dictionary in jinja when key is a variable?


You can use course_codes.get(s.course):

>>> import jinja2>>> env = jinja2.Environment()>>> t = env.from_string('{{ codes.get(mycode) }}')>>> t.generate(codes={'a': '123'}, mycode='a').next()u'123'


There is no need to use the dot notation at all, you can do:

"{{course_codes[s.course]}}"


I'm using Jinja with Salt, and I've found that something like the following works well:

{% for role in pillar.packages %}  {% for package in pillar['packages'][role] %}    install_{{ package }}:      pkg.installed:        - name: {{ package }}  {% endfor %}{% endfor %}

That is, use the more verbose [ ] syntax and leave the quotes out when you need to use a variable.