Django template: how to show dict whose key has a dot in it? d['key.name']

戏子无情 提交于 2019-12-13 14:33:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!