5

I am reading about templates in Jinja, especially about variables. I would like to ask you for explanation for this sentence about acessing values of the passed to Jinja syntax objects:

Implementation

For the sake of convenience, foo.bar in Jinja2 does the following things 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 same name. Additionally, the attr() filter only looks up attributes.

What is the difference between an item and an attribute?

PS - If it's relevant: I work on dictionaries. I have just read that Jinja enables to access the value with the key as an attribute (dict.key), however I feel confused after reading this part about the order of the processes. The comparison "key-value" pair makes understing the part above more challenging.

fgh
  • 169
  • 1
  • 3
  • 15

2 Answers2

3

In python classes instances have attributes; dictionaries contain items. In a dict an item is a combination of a key and a value

a = object()
a.attribute = 'value'
b = dict()
b['key'] = 'value'
b.items()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JeanRibes
  • 131
  • 1
  • 3
  • Jinja treats dictionaries as class instances, thus we can access their attributes. Firstly, Jinja checks whether the object is an... object and has an attribute - a key. If we use Python layer and dic['key'] syntax, in the beginning we look for dictionary's items. The case I have described is the matter of the priority for Python and Jinja, whether they process an item or an attribute. Am I right? – fgh Jan 04 '20 at 14:22
2

Attributes describes the objects of the class, whereas items are the key-value pairs present in the dictionaries.

The way of accessing these also matches with its priority rules: 1. Attributes of objects are accessed with '.' operator. 2. Key-Value pairs of dictionaries are accessed using getitem or '[]' operator.