【问题标题】:Why can't I use this django template variable in conditions?为什么我不能在条件下使用这个 django 模板变量?
【发布时间】:2018-08-09 12:42:00
【问题描述】:

advice here 之后,我可以访问模板中的 allowed_contributors 变量并且可以将其打印出来,但在任何类型的 if-else 语句中使用它都不起作用。它不会给我一个 500 错误,但它就像是空的一样。

我从模板标签加载的文件:

from django import template
from django.conf import settings
register = template.Library()

@register.simple_tag
def allowed_contributors():
    return getattr(settings, "ALLOWED_CONTRIBUTORS", "")

这是我在模板中添加的内容(顶部没有显示“加载”命令,但我想这一定是有效的)。

<div class="container">
    <h1>Create new project</h1>
    <p> {% allowed_contributors %} </p>
    {% if "true" in allowed_contributors %}
       <p>"true" found in allowed_contributors!</p>
    {% endif %}
    {% if "false" in allowed_contributors %}
       <p>"false" found in allowed_contributors!</p>
    {% endif %}
</div>

HTML 输出如下所示:

<div class="container">
    <h1>Create new project</h1>
    <p> ('auth', 'false') </p>


</div>

我已尝试多次输出 allowed_contributors 以防第一次被消耗,但似乎没有任何区别。

当我将它用作 if 语句的条件时,是否需要以不同的方式引用它?

如果有帮助,我正在使用 Django 1.8

编辑:提供的任何明智的答案都不适合我,可能是由于我不知道该项目的其他一些配置。我已经通过使用稍微复杂的context_processor solution 来解决它。

【问题讨论】:

    标签: django django-templates django-settings


    【解决方案1】:

    同样的代码也适用于我。

    注意:&lt;p&gt; {% allowed_contributors %} &lt;/p&gt; 必须是&lt;p&gt; {{ allowed_contributors }} &lt;/p&gt;

    也许这会让你的代码失效?

    我明白了

    新建项目

    ('auth', 'false')

    在 allowed_contributors 中发现“假”!

    【讨论】:

    • 感谢您的尝试。我一定错过了你所拥有的东西。我尝试了 {{ allowed_contributors }} 语法,但它对我不起作用!变量未显示。请注意,如果这有所作为,我正在使用 django 1.8。
    【解决方案2】:
    {% allowed_contributors %}
    

    这不会在上下文中设置值,它只是输出标签的结果。

    要赋值,请执行

    {% allowed_contributors as contributors %}
    

    然后就可以显示值了,

    {{ contributors }}
    

    并在其他标签中使用它:

    {% if "true" in contributors %}
       <p>"true" found</p>
    {% endif %}
    

    在 Django 1.8 和更早的版本中,您不能使用 simple_tag 装饰器来执行 {% allowed_contributors as contributors %} 。您需要改用assignment_tag

    @register.assignment_tag
    def allowed_contributors():
        return getattr(settings, "ALLOWED_CONTRIBUTORS", "")
    

    【讨论】:

    • 谢谢,我使用您建议的语法尝试了 assignment_tag,但它的失败方式与其他方式相同。
    • 我已经在 Django 1.8 中使用我的设置文件中的ALLOWED_SETTINGS = ('auth', 'false') 测试了我的答案,它对我有用。
    猜你喜欢
    • 2016-01-18
    • 1970-01-01
    • 2015-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    相关资源
    最近更新 更多