Conditions (if/else)
More often than not, you'll need to display certain portions of content depending on the value of one or more data item. Let's see how this can be done using Liquid.
Using a simple "if"
The simplest condition you can use is an if
statement:
{% if client.isNewClient == true %}
<p>Congrats on your first order!</p>
{% endif %}
The content will be displayed only when the condition is true.
Combining conditions
You can also combine several conditions using and
and or
{% if client.isExistingClient == true and client.orderedRecently == true %}
<p>A fan of our brand, are we? :D</p>
{% endif %}
{% if client.isNewClient == true or client.orderedALongTimeAgo == true %}
<p>Congrats on your first order this year!</p>
{% endif %}
Inverse condition with "unless"
If you want to inverse the condition unless
is your friend:
{% unless client.isNewClient %}
<p>Nice to see you again!</p>
{% endunless %}
In this case, the code would be equivalent to
{% if client.isNewClient != true %}
<p>Nice to see you again!</p>
{% endif %}
Doing both with "if ... else"
A bit more frequent than unless
the if ... else
statement allows specifying both cases:
{% if client.isNewClient == true %}
<p>Congrats on your first order!</p>
{% else %}
<p>Nice to see you again!</p>
{% endif %}
Multiple conditions with "if ... elsif ... else"
There might be cases where you need to check for multiple conditions to find the right content. For this cases the if ... elsif ... else
statement is the solution:
{% if client.isNewClient == true %}
<p>Congrats on your first order!</p>
{% elsif client.fullName == "Peter Parker" %}
<p>Welcome back Spide… hum… Mr Parker.</p>
{% else %}
<p>Nice to see you again {{client.fullName}}!</p>
{% endif %}
Dispatch according to a single variable
If you want to insert content according to the value of a single variable, you can trade the if ... elsif ... else
statement with a simple case ... when ... end
statement:
{% case client.fullName %}
{% when "Peter Parker" %}
<p>Welcome back Spide… hum… Mr Parker.</p>
{% when "Dianna Price" %}
<p>Nice to see you again WonderW… I mean… Miss Price.</p>
{% else %}
<p>Hello again {{client.fullName}}!</p>
{% endcase %}
Last updated
Was this helpful?