[Django]-"bar" in a Django template expression is a literal?

4👍

Variables can not be used in the dot notation after the .. Everything after the dot is interpreted as a string.

For example, if you have a bar variable and foo passed in a template context. foo is a dictionary {'hello': 'world'}, bar is a string hello.

foo.bar in this case won’t return world since it will be evaluated to foo['bar'].

Demo:

>>> from django.template import Template, Context
>>> t = Template("{{ foo.bar }}")
>>> c = Context({'foo': {'hello': 'world'}, 'bar': 'hello'})
>>> t.render(c)
u''

What if foo has a key bar:

>>> c = Context({'foo': {'bar': 'world'}, 'bar': 'hello'})
>>> t.render(c)
u'world'

Hope this makes things clear to you.

👤alecxe

Leave a comment