简体   繁体   中英

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

{{profile.first-name.value}}

My variable is hypeh only...I wish I could do first_name , but many variables are hyphens. However, due to this problem, I can't display my variables in the template. Why?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM