Home > Back-end >  Liquid: How to combine two "UNLESS" conditions?
Liquid: How to combine two "UNLESS" conditions?

Time:10-13

I am working in Shopify liquid, and I'm looking for a clear and easy way to run a code (in this case initialize jquery) only if two conditions are NOT true.

  1. The template is NOT the cart
  2. The template is NOT a product template with more than one product variant.

In these cases I already initialized JQuery before with more simple IF- conditions. So now I want to avoid initializing JQuery again for these cases.

Can I use this:

{% unless template contains 'cart' or template contains 'product' and product.variants.size > 1 %}
  {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
{% endunless %}

Is it clear that "and" is referring to the 'product'-template? So like If X != true OR (Y != true AND Z = true)?

Otherwise, do I need to use the following in order to make sure JQuery is not initialized twice?

{% unless template contains 'cart' %}
    {% unless template contains 'product' and product.variants.size > 1 %}
        {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
    {% endunless %}
{% endunless %}
{% unless template contains 'product' and product.variants.size > 1 %}
    {% unless template contains 'cart' %}
        {{ 'jquery-2.2.3.min.js' | asset_url | script_tag }}
    {% endunless %}
{% endunless %}

CodePudding user response:

Your solution

First off the second alternative you proposed with the nested code will work in either the two forms:

  1. With cart check outside and product inside
  2. With product check outside and cart inside

General mechanism

Shopify Liquid evaluates operators like and and or in {% if %} and {% unless %} statements from right to left so for example if you have:

<div>

  {% unless false or false and true %}
    {{"The evaluated condition is false"}}
  {% else %}
    {{"The evaluated condition is true"}}
  {% endunless %}

</div>

This will output {{"The evaluated condition is false"}} because:

  1. false and true evaluates to false
  2. false or false evaluates to false
  3. {% unless false %} outputs {{"The evaluated condition is false"}}

I consider a single {% unless %} statement neater and would avoid the nesting but you can go with either solution.

  • Related