Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline if condition in django templates

My if statement in django template is too long. I want to break that into multiple lines.

    {% if ABCDEFGH == BENDHSS and asdasd == asdasdas or asasdas == asdasdd and dasdasdsa == asdasdass or ghgfgsd == efdscsdfg and sgrtvsd == acsdfer %}

I want to break the above line of code into multiple lines. In python, We break it with a backward slash("\").

    if ABCDEFGH == BENDHSS and asdasd == asdasdas or \
        asasdas == asdasdd and dasdasdsa == asdasdass or \
        ghgfgsd == efdscsdfg and sgrtvsd == acsdfer:

Could anyone let me know how we do it in django?

like image 379
GSP Avatar asked Sep 02 '25 09:09

GSP


2 Answers

Unfortunately you can not. Instead of using those long names you can do this

{% with a as ABCDEFGH %}
{% with b as BENDHSS %}
{% with c as asdasdas %}
.
.
.
.

   {% if a == b and asdasd == c or asasdas == asdasdd and dasdasdsa == asdasdass or ghgfgsd == efdscsdfg and sgrtvsd == acsdfer %}

{% endwith %}
{% endwith %}
{% endwith %}

This workaround is good enough if you want to fly underthe linters radar.


Or you can pass those vars in a list and iterate over them

like image 195
Ojas Kale Avatar answered Sep 04 '25 22:09

Ojas Kale


You can not split that expression in the if tag, but you can assign the expression, in your python code, to a new variable and instead pass that to template. e.g.

new_var = ABCDEFGH == BENDHSS and asdasd == asdasdas or \
          asasdas == asdasdd and dasdasdsa == asdasdass or \
          ghgfgsd == efdscsdfg and sgrtvsd == acsdfer:

and then pass new_var to the template.

like image 23
saleem Avatar answered Sep 04 '25 23:09

saleem