Parentheses in django if statement

13,909

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

Share:
13,909

Related videos on Youtube

user49411
Author by

user49411

Updated on September 14, 2022

Comments

  • user49411
    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
      Mihai Zamfir over 9 years
      leave it without paranthesis. I think it works ;)
    • Aamir Rind
      Aamir Rind over 9 years
      You 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
    Mihai Zamfir over 9 years
    I wouldn't put this logic into a view but rather use a custom tag
  • mehmet
    mehmet almost 8 years
    What if one of those variables need to be a loop iteration variable? django disappointed me about this.
  • Hassan Baig
    Hassan Baig over 5 years
    Could you provide a link to the official documentation as well? Helpful answer
  • Daniel W.
    Daniel W. almost 4 years
    And inverted: {% if athlete_list and coach_list or athlete_list and cheerleader_list %} would equal if athlete_list and (coach_list or cheerleader_list)