Why can't I do a hyphen in Django template view?

前端 未结 2 1120
礼貌的吻别
礼貌的吻别 2021-01-19 15:36
{{profile.first-name.value}}

My variable is hypeh only...I wish I could do first_name, but many variables are hyphens. However, du

相关标签:
2条回答
  • 2021-01-19 16:18

    OrderedDict dictionary types support hyphens: 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)
  • 2021-01-19 16:28

    The hyphen is an operator in Python. It would work better if you swapped all hyphens for underscores.

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