问题
I have a dictionary like this:
dict_name['keyname.with.manydots']
Problem: I can't do a
{{ dict_name.keyname.with.manydots }}
I know it's not possible to do this with Django's templating.. but what is the best work-around you've found? Thanks!
回答1:
You could write a custom template filter:
from django import template
register = template.Library()
@register.filter
def get_key(value, arg):
return value.get(arg, None)
And in your template
{{ my_dict|get_key:"dotted.key.value" }}
回答2:
One possible solution, is to create a template tag with the dictionary as the variable and the key as the argument. Remember to emulate Django's default behavior for attribute lookups that fail, this should not throw an error, so return an empty string.
{{ dict_name|get_value:"keyname.with.manydots" }}
@register.filter
def get_value(dict_name, key_name):
return dict_name.get(key_name, '')
来源:https://stackoverflow.com/questions/11801061/django-template-how-to-show-dict-whose-key-has-a-dot-in-it-dkey-name