为什么我不能在条件中使用这个django模板变量?

问题描述 投票:0回答:2

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

我从templatetags加载的文件:

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

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

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

<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
2个回答
1
投票

相同的代码适合我。

注意:<p> {% allowed_contributors %} </p>需要是<p> {{ allowed_contributors }} </p>

也许这会丢掉你的代码?

我知道了

创建新项目

('auth','false')

allowed_contributors中发现“false”!


1
投票
{% allowed_contributors %}

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

要分配值,请执行

{% allowed_contributors as contributors %}

然后你可以显示值,

{{ contributors }}

并在其他标签中使用它:

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

在Django 1.8及更早版本中,你不能用{% allowed_contributors as contributors %} 装饰器做simple_tag。你需要使用assignment_tag代替。

@register.assignment_tag
def allowed_contributors():
    return getattr(settings, "ALLOWED_CONTRIBUTORS", "")
© www.soinside.com 2019 - 2024. All rights reserved.