Conditional statements help us implement the logic of the control flow in programming (well, in this case templating) language. Basically, these statements determine will a block of code run, or not, depending on if certain conditions are met.
The most prominent conditional statement is if / else, which, in practical terms says: if this condition is met, do this, and if not, do something else (or nothing at all).
If / else statements in Shopify Liquid
An if / else statement in Shopify liquid may look like this:
{% if product.tags contains 'Out of stock' %} <p>Out of stock.</p> {% else %} <p>In stock.</p> {% endif %}
So what we are saying to Shopify with this block of code is this:
“Hey, Shopify, check if you have any products that are tagged with ‘Out of stock’. If you do, print a paragraph of text “Out of stock”, and if you don’t, then write “In stock”.
What if you have multiple conditions?
In this case, we will add an {% elsif %} statement:
{% if product.tags contains 'Out of stock' %} <p>Out of stock.</p> {% elsif product.tags contains 'Only two left' %} <p>We have only two of these left in stock. Hurry up to reserve yours!</p> {% else %} <p>The stock is full!</p> {% endif %}
As in other languages, we can also use the != (is not) equality operator, for example. Liquid has its own syntax for it:
{% unless %}
{% endunless %}
You can also combine conditions, and also use “or” logical operator, like this for example:
{% unless collection.handle contains "tom-waits" or collection.handle contains "cold-beer" or collection.handle contains "warm-women" %} Run this block of code. {% endunless %}
Another example might be:
{% if page_description != blank %} <meta name="description" content="{{ page_description | escape }}"> {% else %} <meta name="description" content=“My meta description for pages that do not have the meta description entered."> {% endif %}
So, if my page has a meta description entered, use the default, otherwise add this description: “My meta description for pages that do not have the meta description entered.”
There are also some other options, such as switch/case which you can find more details on in the official Shopify liquid documentation.
Leave a comment