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

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?

+4
source share
1 answer

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

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

{{ object[att] }}

or you can use attr()filter :

{{ object|attr(att) }}

In the Variables section of the template design documentation:

(.) Python __getitem__ "[]".

:

{{ foo.bar }}
{{ foo['bar'] }}

, :

foo['bar'] :

  • 'bar' foo. (foo.__getitem__('bar'))
  • , bar foo. (getattr(foo, 'bar'))
  • , undefined.
+7

Source: https://habr.com/ru/post/1628820/


All Articles