使用`With`标签在Django模板中反转一个布尔值?

时间:2013-07-28 18:58:39

标签: python django django-templates django-views

我想将值传递给include标记,该标记是传入的变量的OPPOSITE。

这是我尝试过的(基本上):

{% with s_options as not disp %}
    {% include "e.html" with show_options=s_options only %}
{% endwith %}

有没有办法做我想做的事?

2 个答案:

答案 0 :(得分:4)

不确定这是否是最佳解决方案,但我刚刚制作了一个新的过滤器:

from django import template

register = template.Library()


@register.filter(name="not_value")
def not_value(true_value):
    return not true_value

然后做了:

{% load not_value %}
{% with s_options=disp|not_value %}  {# WILL NOT WORK WITH "as" #}
    {% include "e.html" with show_options=s_options only %}
{% endwith %}

请注意,这可能也有效(尽管我还没试过):

{% include "e.html" with show_options=s_options|not_value only %}

答案 1 :(得分:4)

使用内置过滤器yesno这有点骇人听闻,但它有效:

{% with reversed_value=original_value|yesno:',True' %}
    {# Do something #}
{% endwith %}

请注意'True'之前的逗号。它的工作方式是yesno如果原始值为True将返回一个空字符串,如果你对它进行任何布尔操作,它将评估为False。