【问题标题】:"bar" in a Django template expression is a literal?Django模板表达式中的“bar”是文字吗?
【发布时间】:2014-05-15 18:04:20
【问题描述】:

阅读 Django 文档

请注意,像 {{ foo.bar }} 这样的模板表达式中的“bar”将被解释为文字字符串,而不使用变量“bar”的值(如果模板上下文中存在变量“bar”)

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

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

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

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

    例如,如果您有一个 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'
    

    希望这能让你明白。

    【讨论】:

    • (因为我对 Django 一无所知)这对所有变量都是如此,还是 bar 特殊?是foo.baz == foo['baz']
    • @AdamSmith 适用于所有变量。应该提到它,对不起。
    • @AdamSmith 我已经澄清了一点答案,看看吧。
    • 非常感谢@alecxe!那么有没有办法获得该功能?即有 bar = 'hello' 并从 {'hello': 'world'} 获取 'world'。或者是一些逻辑最好留给视图而不是在模板中处理?
    • @PavanKMutt 当然,使用自定义模板过滤器:stackoverflow.com/questions/8000022/…
    猜你喜欢
    • 2012-03-30
    • 2014-01-02
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-02
    • 1970-01-01
    • 2021-03-24
    相关资源
    最近更新 更多