Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

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

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

user-name
phone-number

These properties cannot be accessed in templates as follows:

{{ user-name }}

Django throws an exception for this. I'd like to avoid having to convert all of the keys (and sub-table keys) to use underscores just to work around this. Is there an easier way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...