Skip to content Skip to sidebar Skip to footer

Use `with` Tag To Invert A Boolean In Django Template?

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' wi

Solution 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")defnot_value(true_value):
    returnnot 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 %}

Solution 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.

Post a Comment for "Use `with` Tag To Invert A Boolean In Django Template?"