Conditional Tags
Use conditional tags to render sections when variables match certain values. The two major conditional tags are if
and unless
. The if
tag renders its contents if the condition is true, and the unless
tag checks does the same if its condition is false. You can use operators like ==
in conditions to check equivalence.
Use the elsif
and else
tags to check for more than one condition in a block. Only one section will render, and a block will stop checking after one of its tags is selected. The elsif
tag checks for another value, and else
renders its section if no other sections are rendered.
Conditional tags sections should be closed with end followed by the tag name. For example, if
sections are closed with endif
.
Liquid Input
{% if user.username == "john_doe" %}
Welcome back!
{% elsif user.username == "jane_doe" %}
Hi Jane!
{% else %}
Who are you?
{% endif %}
{% unless user.username == "jane_doe" %}
You aren't Jane!
{% endunless %}
HTML Output
If user.username
is john_doe
.
Welcome back!
You aren't Jane!
If user.username
is jane_doe
.
Hi Jane!
If user.username
is jake_doe
.
Who are you?
You aren't Jane!
Case & When Tags
If you have a large number of conditions repeatedly checking a single value, like user.username
, it can be easier to use case
and when
tags.
Liquid Input
{% case user.username %}
{% when 'john_doe' %}
Welcome back!
{% when 'jane_doe' %}
Hi Jane!
{% else %}
Who are you?
{% endcase %}
HTML Output
If user.username
is john_doe
.
Welcome back!
If user.username
is jane_doe
.
Hi Jane!
If user.username
is jake_doe
.
Who are you?