Quantcast
Channel: Django template - dynamic variable name - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Joe for Django template - dynamic variable name

$
0
0

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'.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>