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

社会主义新天地 提交于 2020-05-09 21:51:49

问题


With regular python, I could get getattr(object, att) but in Jinja2, I get:

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

How can I use it?


回答1:


Jinja2 is not Python. It uses a Python-like syntax, but does not define the same built-in functions.

Use subscription syntax instead; you can use attribute and subscription access interchangeably in Jinja2:

{{ object[att] }}

or you can use the attr() filter:

{{ object|attr(att) }}

From the Variables section of the template designer documentation:

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


来源:https://stackoverflow.com/questions/35407008/using-getattr-in-jinja2-gives-me-an-error-jinja2-exceptions-undefinederror-ge

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