Django template - dynamic variable name

后端 未结 2 1440
孤独总比滥情好
孤独总比滥情好 2020-12-20 20:54

Good Afternoon,

How can I use a variable variable name in Django templates?

I have a custom auth system using context, has_perm che

相关标签:
2条回答
  • 2020-12-20 21:17

    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

    0 讨论(0)
  • 2020-12-20 21:24

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

    0 讨论(0)
提交回复
热议问题