Django 模板表达式中的 "bar" 是字面量吗?
在阅读Django文档时
注意,在像{{ foo.bar }}这样的模板表达式中,“bar”会被当作一个普通的字符串来处理,而不是使用模板上下文中如果存在的“bar”变量的值。
这是不是意味着“bar”是某种特殊的关键词?或者说一个叫“bar”的变量(不属于对象foo)不能像上面那样被访问?
我知道我这里缺少了一些简单的东西,但到底是什么呢?
1 个回答
4
在点符号后面,变量是不能直接使用的。点后面的内容会被当作字符串来处理。
举个例子,如果你有一个叫 bar
的变量,还有一个叫 foo
的字典,字典的内容是 {'hello': 'world'}
,而 bar
是一个字符串 hello
。
在这种情况下,foo.bar
不会返回 world
,因为它会被解释成 foo['bar']
。
演示:
>>> from django.template import Template, Context
>>> t = Template("{{ foo.bar }}")
>>> c = Context({'foo': {'hello': 'world'}, 'bar': 'hello'})
>>> t.render(c)
u''
如果 foo
有一个键是 bar
,那会怎样呢:
>>> c = Context({'foo': {'bar': 'world'}, 'bar': 'hello'})
>>> t.render(c)
u'world'
希望这样能让你更明白。