简体   繁体   中英

Django template IF condition with logical breckets and precedence order

In my django template I have

{% if object_not_readonly and user_is_worker or user_is_admin %}

Django doc tell me

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or

I think this is not obvious way to declare logical precedence in IF clause.

Question is :

Is it something like {% if object_not_readonly and ( user_is_worker or user_is_admin ) %} condition in django template language, with obvious clause like if A and (C or B) and (not Z) ?

It's not clear what you're asking here, or what result you are trying to achieve with your example statement:

{% if object_not_readonly and user_is_worker or user_is_admin %}

To clarify what they mean in the reference docs by "Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or", the above statement would be evaluated as:

{% if (object_not_readonly and user_is_worker) or user_is_admin %}

which is not the same as {% if object_not_readonly and ( user_is_worker or user_is_admin ) %}

In order to be perfectly safe, I would split it up like this:

{% if object_not_readonly %} 
    {% if user_is_worker or user_is_admin %}

        ...

    {% endif %}
{% endif %}

According the documentation, if you can't solve your problem with the default precedence then you must use nested if. As Adam mentioned already:

{% if object_not_readonly %} 
   {% if user_is_worker or user_is_admin %}

    ...

   {% endif %}
{% endif %}

https://docs.djangoproject.com/en/4.0/ref/templates/builtins/#std-templatetag-if

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags. I hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM