Is it possible to create a Django template tag which evaluates to a boolean?
Eg, can I do:
{% if my_custom_tag %}
..
{% else %}
..
{% endif %}
At the moment I've written it as an as tag, which works fine like this:
{% my_custom_tag as var_storing_result %}
But I was just curious if I could do it the other way as I think it'd be nicer if I didn't have to assign the result to a variable first.
Thanks!
The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output. One can use various boolean operators with Django If Template tag.
{% %} 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.
Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .
The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.
One alternative might be to define a custom filter that returns a boolean:
{% if my_variable|my_custom_boolean_filter %}
but that will only work if your tag depends on some other template variable.
Actually.. what you can do is register tag as assignment_tag
instead of simple_tag
Then in your template you can just do {% my_custom_tag as var_storing_result %}
one time and then regular if blocks where ever you want to evaluate the boolean. Super useful! For example
Template Tag
def my_custom_boolean_filter:
return True
register.assignment_tag(my_custom_boolean_filter)
Template
{% my_custom_boolean_filter as my_custom_boolean_filter %}
{% if my_custom_boolean_filter %}
<p>Everything is awesome!</p>
{% endif %}
Assignment Tag Official Doc
You'd have to write a custom {% if %} tag of some sort to handle that. In my opinion, it's best to use what you already have in place. It works well, and is easy for any other developers to figure out what's going on.
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