Django TemplateTag evaluates boolean value

Is it possible to create a Django template tag that computes a boolean?

For example, can I do:

{% if my_custom_tag %} .. {% else %} .. {% endif %} 

At the moment, I wrote it as a tag that works fine as follows:

 {% my_custom_tag as var_storing_result %} 

But I was just curious if I could do it differently, because I think it would be better if I didn't have to assign the result to the variable first.

Thanks!

+7
source share
3 answers

You need to write your own tag {% if%} of some type to process it. In my opinion, it is best to use what you already have. It works well, and it’s easy for other developers to understand what is going on.

+2
source

An alternative would be to define a custom filter that returns a boolean:

 {% if my_variable|my_custom_boolean_filter %} 

but this will only work if your tag depends on some other template variable.

+5
source

Actually .. what you can do is register the tag as assignment_tag instead of simple_tag . Then in your template you can simply do {% my_custom_tag as var_storing_result %} once, and then regularly if there are blocks, wherever you want to evaluate a boolean value. Super helpful! 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 %} 

Formal agreement with destination tag

+5
source

All Articles