Skip to main content
 首页 » 编程设计

python之Django 模板表达式中的 "bar"是文字吗

2024年11月01日27虾米哥

阅读 Django 文档

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

这是否意味着“bar”是一些特殊的关键字?或者不能像上面那样访问名为“bar”的变量(不属于对象 foo)?

我知道我在这里遗漏了一些简单的东西,但是什么?

请您参考如下方法:

. 后的点号不能使用变量。点之后的所有内容都被解释为字符串。

例如,如果您在模板上下文中传递了一个 bar 变量和 foo。 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' 

希望这能让您清楚。