问题
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