Accessing dict elements with leading underscores in Django Templates

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

I am trying to access elements of a dict with keys that start with the underscore character. For example:

my_dict = {"_source": 'xyz'}

I'm trying to access them in a Django template. Obviously I realise that you can't access underscored python variables from a Django template (because they are considered private in Python) but this is a dict object where any immutable object is a valid key.

I can't access the above dict in a Django template using {{ my_dict._source }} so I assume Django is preventing it. Is that accurate?

I am kind of hoping Django does something sane with variables that start with underscore like still doing dict lookups (the first thing is supposedly tries) but refuses to do attribute lookups, method calls and list index lookups since an underscored prefixed variable would be invalid. I am quickly loosing hope though.

For the record, I know someone will suggest to just change the dict but this is actually a multi-levelled dictionary returned by the rawes library when executing REST API request on a ElasticSearch instance.

回答1:

The docs mention that you can't have a variable start with an underscore:

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore (but they must not start with an underscore) or a dot.

but you can easily write a custom template filter to mimic the dictionary's get method:

@register.filter(name='get') def get(d, k):     return d.get(k, None) 

and

{{ my_dict|get:"_my_key" }} 


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