3

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?

MeLight
  • 5,454
  • 4
  • 43
  • 67
  • The answer you've linked to says nothing about Django – MeLight Oct 08 '14 at 10:42
  • 1
    Voting for reopen. This is not something that can be done with a templatefilter btw, you could do it with a templatetag though. – Wolph Oct 08 '14 at 10:53
  • Here's a similar question: http://stackoverflow.com/questions/17148544/django-template-dynamic-variable-name – Wolph Oct 08 '14 at 10:54

2 Answers2

1

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 }}
Uri
  • 2,992
  • 8
  • 43
  • 86
0

My opinion is that if you're making decisions based on something that was already known, that computation should have happened before you rendered the template.

You could also use a dict i.e. var = {"a":"foo", "b":"bar"} You can't index dicts directly in the template so depending on what you are trying to achieve either iterate over the dict or use a template filter like in this question, here is the link to the ticket.

OllyTheNinja
  • 566
  • 3
  • 16