4

Suppose I have a django template with the following context:

data1 = "this is data1"
data2 = "this is data2"
data_name = "data2"

Now I know the value of data_name(assume it's "data2"), is it possible to use it to access the variable data2?

To make my intention clearer, this is how you might do it with Python

>>> a = 1
>>> b = 2
>>> name = 'a'
>>> locals()[name]
1
>>> name = 'b'
>>> locals()[name]
2
1
  • 1
    +1 This is a good question, in my opinion there is no way to do that, but let's wait. Commented Jan 22, 2014 at 10:48

2 Answers 2

6

With builtin template filters, tags, it's impossible. You should define custom tags to do it.

Example:

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def get_by_name(context, name):
    return context[name]

Example usage (assume tag is defined in APP_DIR/templatetags/name.py):

>>> from django.template import Template, Context
>>> t = Template('''
... {% load name %} {# Don't forget to load #}
... {% get_by_name data_name %}
... ''')
>>> output = t.render(Context({
...     'data1': 'this is data1',
...     'data2': 'this is data2',
...     'data_name': 'data2',
... }))
>>> print(output)


this is data2
Sign up to request clarification or add additional context in comments.

2 Comments

Good use of inner variable used by templatetags, context.
Great answer! I believe this is the solution.
0

This custom filter will allow you to get a given property of a given context variable. In your app folder, create a folder called templatetags and insert this content into templatetags/custom_tags.py:

from django import template

register = template.Library()

@register.filter()
def get_key(value, arg):
    if arg in value:
        return value[arg]
    else:
        return ''

Here is an example using this in a template that handles a a form (there is a variable called "form" in the context). This gets the property "username" of the context variable "form.errors".

{% load custom_tags %}

{{ form.errors | get_key:"username" }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.