Let's say I have two variables passed to a template: var_a and var_b. Is there a way to address them dynamically, or in other words construct the variable name from strings? Something like PHP's $$var_name.
For example if i have a letter variable with holds the value a or b, I'd like to render var_a by writing something like:
{{"var_"|some_sort_of_concat:letter}}
and get the value of var_a or var_b depending on the value of letter. Is such a thing possible?
You can create a dictionary with your variable names as keys and their values as values, then create a template filter to get the dictionary value by the given variable name. The variable name can also be a variable taken from a list or anything else:
d = {"var_a": "a", "var_b": "b"}
Send d to the template and create a template filter "get_dictionary_value":
def get_dictionary_value(d, key):
try:
if (key in d):
return d[key]
except:
pass
return ""
And then in the template:
{{ d|get_dictionary_value:"var_a" }}
Or:
{% for key in l %}
{{ d|get_dictionary_value:key }}
{% endfor %}
By the way, the value of d[key] can also be a dictionary and you can apply this filter again (and again...):
{{ d|get_dictionary_value:key1|get_dictionary_value:key2 }}
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