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

时间:2018-03-01 12:33:48

标签: django django-templates django-settings

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来解决这个问题。

2 个答案:

答案 0 :(得分:1)

相同的代码对我有用。

注意:<p> {{ allowed_contributors }} </p>必须为private fun getData() { val disposable = dataRepository.getDataFromRepository(String: itemId) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ _ -> // I got my data }, { // error }) compositeDisposable.add(disposable) }

也许这会丢掉你的代码?

我看到了

  

创建新项目

     

('auth','false')

     在allowed_contributors中找到

“false”!

答案 1 :(得分: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", "")
相关问题