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

前端 未结 3 1926
执笔经年
执笔经年 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:01

    Unfortunately, I think you may be out of luck. From the docs:

    Variable names must consist of any letter (A-Z), any digit (0-9), an underscore or a dot.

    0 讨论(0)
  • 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 :-)

    0 讨论(0)
  • 2020-12-04 02:22

    OrderedDict dictionary types support dashes: https://docs.python.org/2/library/collections.html#ordereddict-objects

    This seems to be a side effect of the implementation of OrderedDict. Notice below that the key value pairs are actually passed in as sets. I would bet that the implementation of OrderedDict doesn't use the "key" passed in the set as a true dict key thus getting around this issue.

    Since this is a side-effect of the implementation of OrderedDict, it may not be something you want to rely on. But it works.

    from collections import OrderedDict
    
    my_dict = OrderedDict([
        ('has-dash', 'has dash value'), 
        ('no dash', 'no dash value') 
    ])
    
    print( 'has-dash: ' + my_dict['has-dash'] )
    print( 'no dash: ' + my_dict['no dash'] )
    

    Result:

    has-dash: has dash value
    no dash: no dash value
    
    0 讨论(0)
提交回复
热议问题