I'm trying to retrieve entries from a python dictionary in jinja2, but the problem is I don't know what key I want to access ahead of time - the key is stored in a variable called s.course
. So my problem is I need to double-substitute this variable. I don't want to use a for
loop because that will go through the dictionary way more than is necessary. Here's a workaround that I created, but it's possible that the s.course
values could change so obviously hard-coding them like this is bad. I want it to work essentially like this:
{% if s.course == "p11" %} {{course_codes.p11}} {% elif s.course == "m12a" %} {{course_codes.m12a}} {% elif s.course == "m12b" %} {{course_codes.m12b}} {% endif %}
But I want it to look like this:
{{course_codes.{{s.course}}}}
Thanks!
You can assign a dictionary value to a variable in Python using the access operator [].
To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.
You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist. Specify the key as the first argument. The corresponding value is returned if the key exists, and None is returned if the key does not exist.
In Python to get all values from a dictionary, we can use the values() method. The values() method is a built-in function in Python and returns a view object that represents a list of dictionaries that contains all the values.
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]}}"
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