Good Afternoon,
How can I use a variable variable name in Django templates?
I have a custom auth system using context
, has_perm
che
You can try like this,
{{ dict|key:key_name }}
Filter:
def key(d, key_name):
return d[key_name]
key = register.filter('key', key)
More information, django ticket
You're best off writing your own custom template tag for that. It's not difficult to do, and normal for this kind of situation.
I have not tested this, but something along these lines should work. Remember to handle errors properly!
def lookup(object, property):
return getattr(object, property)()
register.simple_tag(lookup)
If you're trying to get a property rather than execute a method, remove those ()
.
and use it:
{% lookup has_perm "depauth" %}
Note that has_perm
is a variable, and "depauth"
is a string value. this will pass the string for lookup, i.e. get has_perm.depauth
.
You can call it with a variable:
{% with arg_value="depauth_other_value" %}
{% lookup has_perm arg_value %}
{% endwith %}
which means that the value of the variable will be used to look it up, i.e. has_perm.depauth_other_value
'.