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

前端 未结 1 409
甜味超标
甜味超标 2021-02-05 14:11

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

jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: \'ge         


        
相关标签:
1条回答
  • 2021-02-05 14:26

    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.
    0 讨论(0)
提交回复
热议问题