Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django TemplateTag evaluating to a boolean

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!

like image 784
Ludo Avatar asked May 18 '11 16:05

Ludo


People also ask

How can check Boolean value in if condition Django?

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.

What does {% %} mean in Django?

{% %} 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.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .

What is with tag in Django template?

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.


3 Answers

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.

like image 64
Daniel Roseman Avatar answered Sep 24 '22 03:09

Daniel Roseman


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

like image 45
Jose Browne Avatar answered Sep 26 '22 03:09

Jose Browne


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.

like image 31
Alex Jillard Avatar answered Sep 24 '22 03:09

Alex Jillard