Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parentheses in django if statement

Tags:

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.

like image 931
user49411 Avatar asked Dec 15 '14 15:12

user49411


2 Answers

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

like image 166
Sven Avatar answered Sep 29 '22 07:09

Sven


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

like image 42
dm03514 Avatar answered Sep 29 '22 08:09

dm03514