Using getattr in Jinja2 gives me an error (jinja2.exceptions.UndefinedError: 'getattr' is undefined)

Using getattr in Jinja2 gives me an error (jinja2.exceptions.UndefinedError: 'getattr' is undefined)

使用常规 python,我可以得到 getattr(object, att) 但在 Jinja2 中,我得到:

jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'getattr' is undefined

如何使用?

Jinja2 不是Python。它使用类似 Python 的语法,但没有定义相同的内置函数。

改为使用订阅语法;您可以在 Jinja2 中交替使用属性和订阅访问:

{{ object[att] }}

或者您可以使用 attr() filter:

{{ object|attr(att) }}

来自模板设计器文档的Variables section

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'] }}

并在同一部分进一步解释实施细节:

foo['bar'] works mostly the same with a small difference in sequence:

  • 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.