Is there a way to negate a python boolean variable in a template using Django? I've tried both of the following:
<td>{{ !variable_name }}</td>
<td>{{ not variable_name }}</td>
But both gave me a TemplateSyntaxError.
I realize that I could do:
<td>{% if variable_name %} False {% else %} True {% endif %}</td>
But this seems really clunky. I was hoping there might be a cleaner method.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Django for loop counter All the variables related to the counter are listed below. forloop. counter: By using this, the iteration of the loop starts from index 1. forloop. counter0: By using this, the iteration of the loop starts from index 0.
Definition and Usage In master templates the block tag is a placeholder that will be replaced by a block in a child template with the same name. In child templates the block tag is content that will replace the placeholder in the master template with the same name.
lorem tag displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.
What about the yesno template tag?
{{ value|yesno:"False,True" }}
"not" should work, according to this example from the Django docs:
{% if not athlete_list %}
There are no athletes.
{% endif %}
You can find the example here: https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#boolean-operators
If you want to directly get the string representation of a boolean, i'm afraid you have to go what you describe as clunky. {{ variable }} puts out a string representation of the variables content or calls a function.
edit:
If you are really in need of getting the inverse value of a boolean, i would suggest to create a simple templatetag for that:
from django import template
register = template.Library()
@register.simple_tag
def negate(boolean):
return (not boolean).__str__()
put that in your_app/templatetags/templatetags.py and you can use it in your template like this:
{% negate your_variable %}
quite costly, i would stick with garnertb's answer.
Another way to do it is by using the add
filter like this:
{{ variable_name|add:"-1" }}
True
is 1
, so, it'll become 0
which is False
False
is 0
, so, it'll become -1
which is True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With