本文介绍了在Django模板中访问带有下划线的dict元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下划线字符开头的键访问dict的元素。例如:



my_dict = {_source:'xyz'}



我试图在Django模板中访问它们。显然,我意识到你不能从Django模板访问强调的python变量(因为它们在Python中被认为是私有的),但是这是一个dict对象,其中任何不可变对象是一个有效的键。



我无法使用{{my_dict._source}}访问Django模板中的上述dict,所以我假设Django正在阻止它。是准确吗?



我有点希望Django对变量开始的一些变数,它们从下划线开始,就像仍然在进行dict查找(第一件事据说是尝试),但拒绝进行属性查找,方法调用和列表索引查找,因为下划线的前缀变量将无效。我很快就失去了希望。



为了记录,我知道有人会建议只要更改dict,但这实际上是由rawes库返回的多级字典在ElasticSearch实例上执行REST API请求时。

解决方案

以模拟字典的方法:

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

  {{my_dict | get: _my_key}} 


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.

解决方案

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

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" }}

这篇关于在Django模板中访问带有下划线的dict元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 14:37