The foundation of conditional statements can be boiled down to this: if this is true then run this code. You can also expand on that: if this is true then run this code, if not run a different code. You can get carried away on different ways to mold a statement. Here is the Liquid code for conditional statements:
{% assign us_state = "Arizona" %}
{% if us_state == "Arizona" %}
It's over 100 degrees today!
{% endif %}
The "if" statement starts with being wrapped in curly braces and percent signs {% %} with a condition included. In this example it is checking if the us_state equals "Arizona". If it is true then it shows "It's over 100 degrees today!". Then the statement is closed with {% endif %}.
Let's expand the condition with an else statement:
{% assign us_state = "California" %}
{% if us_state == "Arizona" %}
It's over 100 degrees today!
{% else %}
It's a cool day.
{% endif %}
Now the values don't match up, it will go to the else statement and show "It's a cool day". This is because the else statement always results in true. We can also chain an if statement with elsif:
Note: Make sure it is "elsif" not "elseif" because it will cause Liquid to throw an error. I've made this mistake on more than one occasion.
{% assign us_state = "California" %}
{% if us_state == "Arizona" %}
It's over 100 degrees today!
{% elsif us_state == "California" %}
It's a cool day.
{% else %}
It's a nice day.
{% endif %}
You can only use elsif before else statements because as stated before else statement always results in true preventing anymore conditions to be checked.
// Don't do this
{% assign us_state = "California" %}
{% if us_state == "Arizona" %}
It's over 100 degrees today!
{% else %}
It's a cool day.
{% elsif us_state == "California" %}
It's another cool day.
{% endif %}
There will be time you need to check your theme settings (We'll learn about this soon). A best practice to follow is checking if the setting has been applied. We do this by comparing it to the keyword blank.
{% if settings.section_title == blank %}
<h1>{{ settings.section_title }}</h1>
{% endif %}
If the setting is not an empty string, show the enclosed code.
Multiple conditional statements
You can also chain more than one condition inside an if statement. Using other comparison operators we learned, here is our example:
{% if number_rating > 9 and number_rating < 11 %}
You are a 10!
{% endif %}
Having trouble? Ask for help.