How do I access dictionary keys that contain hyphens from within a Django template?

前端 未结 3 1943
执笔经年
执笔经年 2020-12-04 01:24

We have a system built on a custom database, where many of the attributes are named containing hyphens, ie:

user-name
phone-number

These pr

3条回答
  •  不知归路
    2020-12-04 02:17

    A custom template tag is probably the only way to go here if you don't want to restructure your objects. For accessing dictionaries with an arbitrary string key, the answer to this question provides a good example.

    For the lazy:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def dictKeyLookup(the_dict, key):
       # Try to fetch from the dict, and if it's not found return an empty string.
       return the_dict.get(key, '')
    

    Which you use like so:

    {% dictKeyLookup your_dict_passed_into_context "phone-number" %}
    

    If you want to access an object's attribute with an arbitrary string name, you could use the following:

    from django import template
    register = template.Library()
    
    @register.simple_tag
    def attributeLookup(the_object, attribute_name):
       # Try to fetch from the object, and if it's not found return None.
       return getattr(the_object, attribute_name, None)
    

    Which you would use like:

    {% attributeLookup your_object_passed_into_context "phone-number" %}
    

    You could even come up with some sort of string seperator (like '__') for subattributes, but I'll leave that for homework :-)

提交回复
热议问题