Parentheses in django if statement
Solution 1
As Mihai Zamfir commented it should work as expected. As Django documentation mentions:
Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:
{% if athlete_list and coach_list or cheerleader_list %}
will be interpreted like:
if (athlete_list and coach_list) or cheerleader_list
https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#boolean-operators
Solution 2
you could do the check in your view and pass a flag to the context.
show_html = user.is_admin or (something.enable_thing and user.can_do_the_thing)
context['show_html'] = show_html
Then in your template you could check the flag
{% if show_html %}
Related videos on Youtube
user49411
Updated on September 14, 2022Comments
-
user49411 over 1 year
How can I do this cleanly in a Django template? Basically if A, or (B and C) , I want to show some HTML.
I basically have this:
{% if user.is_admin or something.enable_thing and user.can_do_the_thing %}
Now, thats a bit ambigious. I tried doing
{% if user.is_admin or (something.enable_thing and user.can_do_thething) %}
But you arent allowed Parentheses. The docs say to use nested ifs (or elifs in this case, i guess, as its an OR) , but I dont want to repeat the same HTML inside 2 if blocks, which sounds horrible.
-
Mihai Zamfir over 9 yearsleave it without paranthesis. I think it works ;)
-
Aamir Rind over 9 yearsYou don't want to use nested if's and also parenthesis are invalid in
if
block, hence clearly framework does not support what you are asking for get over with it and move your complex logic to template tags or views.
-
-
Mihai Zamfir over 9 yearsI wouldn't put this logic into a view but rather use a custom tag
-
mehmet almost 8 yearsWhat if one of those variables need to be a loop iteration variable? django disappointed me about this.
-
Hassan Baig over 5 yearsCould you provide a link to the official documentation as well? Helpful answer
-
Daniel W. almost 4 yearsAnd inverted:
{% if athlete_list and coach_list or athlete_list and cheerleader_list %}
would equalif athlete_list and (coach_list or cheerleader_list)