Variables

Template variables are defined by the context dictionary passed to thetemplate.

You can mess around with the variables in templates provided they are passed inby the application. Variables may have attributes or elements on them you canaccess too. What attributes a variable has depends heavily on the applicationproviding that variable.

You can use a dot (.) to access attributes of a variable in additionto the standard Python getitem “subscript” syntax ([]).

The following lines do the same thing:

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

It’s important to know that the outer double-curly braces are not part of thevariable, but the print statement. If you access variables inside tags don’tput the braces around them.

If a variable or attribute does not exist, you will get back an undefinedvalue. What you can do with that kind of value depends on the applicationconfiguration: the default behavior is to evaluate to an empty string ifprinted or iterated over, and to fail for every other operation.

Implementation

For the sake of convenience, foo.bar in Jinja2 does the followingthings on the Python layer:

  • check for an attribute called bar on foo(getattr(foo, 'bar'))

  • if there is not, check for an item 'bar' in foo(foo.getitem('bar'))

  • if there is not, return an undefined object.

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.

This is important if an object has an item and attribute with the samename. Additionally, the attr() filter only looks up attributes.