3

Reading the Django doc

Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context

Does that mean that "bar" is some special keyword? Or that a variable called 'bar'(not belonging to object foo) can not be accessed like above?

I know I am missing something simple here, but what?

Pavan Kemparaju
  • 1,591
  • 3
  • 16
  • 25

1 Answers1

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
  • 462,703
  • 120
  • 1,088
  • 1,195
  • (Since I don't know anything about Django) Is this true for all variables, or is `bar` special? Is `foo.baz == foo['baz']`? – Adam Smith Apr 03 '14 at 18:21
  • 1
    @AdamSmith true for all variables. Should have mentioned it, sorry. – alecxe Apr 03 '14 at 18:21
  • @AdamSmith I've clarified answer a bit, check it out. – alecxe Apr 03 '14 at 18:26
  • Thank you so much @alecxe! So is there a way to get that functionality? i.e. Have bar = 'hello' and get 'world' from {'hello': 'world'}. Or is that some logic best left to the view than handled at the template? – Pavan Kemparaju Apr 04 '14 at 06:30
  • @PavanKMutt sure, use custom template filter: http://stackoverflow.com/questions/8000022/django-template-how-to-lookup-a-dictionary-value-with-a-variable – alecxe Apr 04 '14 at 12:52