在Jinja2中使用getattr会给我一个错误(jinja2.exceptions.UndefinedError:'getattr'未定义) [英] Using getattr in Jinja2 gives me an error (jinja2.exceptions.UndefinedError: 'getattr' is undefined)
问题描述
使用常规python,我可以得到getattr(object, att)
,但是在Jinja2中,我得到:
With regular python, I could get getattr(object, att)
but in Jinja2, I get:
jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'getattr' is undefined
我如何使用它?
推荐答案
Jinja2不是Python .它使用类似Python的语法,但未定义相同的内置函数.
Jinja2 is not Python. It uses a Python-like syntax, but does not define the same built-in functions.
改为使用订阅语法;您可以在Jinja2中互换使用属性和订阅访问权限:
Use subscription syntax instead; you can use attribute and subscription access interchangeably in Jinja2:
{{ object[att] }}
,或者您可以使用 attr()
过滤器:
or you can use the attr()
filter:
{{ object|attr(att) }}
从 变量部分模板设计器文档:
From the Variables section of the template designer documentation:
除了标准的Python
__getitem__
下标"语法([]
)之外,您还可以使用点(.
)访问变量的属性.
You can use a dot (
.
) to access attributes of a variable in addition to the standard Python__getitem__
"subscript" syntax ([]
).
以下几行做同样的事情:
The following lines do the same thing:
{{ foo.bar }}
{{ foo['bar'] }}
并在同一部分中进一步解释实现细节:
and further down in the same section, explaining the implementation details:
foo['bar']
的工作原理几乎相同,只是顺序有所不同:
foo['bar']
works mostly the same with a small difference in sequence:
- 检查 foo 中的项目
'bar'
. (foo.__getitem__('bar')
) - 如果没有,请检查 foo 上名为 bar 的属性. (
getattr(foo, 'bar')
) - 如果没有,则返回未定义的对象.
- check for an item
'bar'
in foo. (foo.__getitem__('bar')
) - if there is not, check for an attribute called bar on foo. (
getattr(foo, 'bar')
) - if there is not, return an undefined object.
这篇关于在Jinja2中使用getattr会给我一个错误(jinja2.exceptions.UndefinedError:'getattr'未定义)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!