if, unless, elsif/else and case/when Conditional Tags in Shopify Liquid
The tags if, unless, elsif/else, case/when are some of the conditional tags used in the Shopify liquid. Control Flow or Conditional Tags determine which block of code should be executed and what content should be rendered based on given conditions. Let us discuss all conditional tags with examples.
if
The if condition tag renders an expression if a specific condition is true
.
{% if name == 'John' %}
Hello, John
{% endif %}
Output:
Hello, John
In the above example Hello, John is rendered only if the value in the variable name
is john.
unless
The unless tag is opposite to the if tag. It executes a block of code if a given condition is not met. See the below example.
{% unless page.title == 'Product' %}
This is not a Product page.
{% endunless %}
Output:
This is not a Product page.
The above code would be the equivalent of doing the following:
{% if page.title != 'Product' %}
This is not a Product page.
{% endunless %}
In this example, the text “This is not a Product page.” is only rendered if the page title is not equal to Product.
elsif / else
The elsif / else tags add more conditions within an if or unless block. You can use the elsif tag to check for multiple conditions. else tag allows you to specify a default expression to execute when no other condition is met. You can use the else tag with the case, if, unless.
{% if name == 'John' %}
Hello, John
{% elsif name == 'Leo' %}
Hello, Leo
{% else %}
Hello, stranger.
{% endif %}
The elsif expression is checked only if the first condition inside the if
tag is not met. In the above example, elsif name == 'Leo'
is checked if if name == 'John'
is failed. If the expression elsif name == ‘Leo’
is true, then it renders Hello, Leo as the output.
case/when
The case/when is a switch statement to compare a variable to different values, and execute a different block of code for each value. case
initializes the switch statement, and when
statements define the various conditions.
An optional else
statement at the end of the case provides code to execute if none of the conditions are met.
{% case name %}
{% when 'John' %}
Hello, John
{% when 'Leo' %}
Hello, Leo.
{% else %}
Hello, stranger.
{% endcase %}
and
The and
operator helps to add additional conditions to a tag. A condition that uses and
will only be true if both the left and the right sides of the condition are true
.
{% if product.title == 'Shirts' and product.price < 10000 %}
These shirts are affordable.
{% endif %}
Output:
These shirts are affordable.
or
The or
operator helps you to add additional conditions to a tag. A condition with an or
will be true if either the left or the right side of the condition is true
.
{% if product.title == 'Shoes' or product.title == 'Chappel' %}
You're buying a foot wear!
{% endif %}
Output:
You're buying a foot wear!