gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:45 25 4
gpt4 key购买 nike

阅读 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 变量和 foofoo 是一个字典{'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'

希望这能让您清楚。

关于python - Django 模板表达式中的 "bar"是文字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22845618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com