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?
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.
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?
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.
0 commentaires:
Enregistrer un commentaire