Search code examples
pythonattributesjinja2

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?


Solution

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