在 Django 模板中访问带有前导下划线的 dict 元素 [英] Accessing dict elements with leading underscores in Django Templates

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

问题描述

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

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

my_dict = {"_source": 'xyz'}

我正在尝试在 Django 模板中访问它们.显然,我意识到您无法从 Django 模板访问带下划线的 Python 变量(因为它们在 Python 中被认为是私有的),但这是一个 dict 对象,其中任何不可变对象都是有效密钥.

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.

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

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?

我有点希望 Django 对以下划线开头的变量做一些理智的事情,比如仍然进行 dict 查找(第一件事应该是尝试)但拒绝进行属性查找、方法调用和列表索引查找,因为带下划线的前缀变量会无效.不过我很快就失去了希望.

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.

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

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:

变量名必须由任意字母 (A-Z)、任意数字 (0-9)、下划线(但不得以下划线开头)或点组成.

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.

但您可以轻松编写自定义模板过滤器 模仿字典的 get 方法:

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)

{{ my_dict|get:"_my_key" }}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆