MattG
MattG

Reputation: 1932

How to make context variable dynamic in django template

Is it possible to append 2 context variables together into a single context variable that is calculated at run-time? For example: if I have {{contextA}} (which equals 1) and {{contextB}} (which equals 'building') and I wanted to add these together to get context {{1building}} How would I do this? I have tried:

{{contextA + contextB}}

{{{{contextA}} + {{contextB}}}}

{{contextA |add: contextB}}

{{contextA contextB}}

I suppose this is not possible and this needs to be done in the view using python, but it would be ideal if I could just combine context variables in the template.

Upvotes: 1

Views: 1244

Answers (1)

Gabriel
Gabriel

Reputation: 1149

U can use {% with template tag as follows (docs here -> https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#with)

{% with newvar=contextA|add:contextB %}
    {{ newvar }}
{% endwith %}

newvar will have a new value if into a forloop where contextA or contextB change it's value.

As you want to show the value of a context variable with it's name equal to newvar value, the way to accomplish it is to create a custom template tag as follows:


@register.simple_tag(takes_context=True)
def dynvarvalue(context, dynvarname):
    """ Returns the value of dynvarname into the context """
    return context.get(dynvarname, None)

I did a small proof of concept:

{% with 1building='1 building value' contextA='1' contextB='building' %}
  {% dynvarvalue contextA|add:contextB %}
{% endwith %}

Which produces the following output, which I think is what you are asking for:

1 building value

Hope this helps.


Note: take into account that if both variables can be transformed to an integer, they will not be concatenated and will be summed as docs says (https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#add)

Note2: I think there are some security caveats to take into account doing this.

Upvotes: 1

Related Questions