Use `With` Tag to invert a boolean in Django Template?

ぐ巨炮叔叔 提交于 2020-01-16 03:28:08

问题


I want to pass a value to an include tag that is the OPPOSITE of a variable passed in.

This is what I tried (basically):

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

Is there any way to do what I want?


回答1:


Not sure if this is the best solution, but I just made a new filter:

from django import template

register = template.Library()


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

And then did:

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

Note that, possibly, this might work as well (though I have not tried):

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



回答2:


This is a bit of a hack using the built in filter yesno, but it works:

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

Note the comma before 'True'. The way it works is that yesno will return an empty string if the original value is True, which will evaluate as False if you're doing any boolean operations on it.



来源:https://stackoverflow.com/questions/17911728/use-with-tag-to-invert-a-boolean-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!