Conditional tags let you execute code only if a certain condition is met. This allows for creating dynamic templates that respond to different states and data.
Executes a block of code only if a condition is true.
{% if condition %}
// code to execute if condition is true
{% endif %}
The condition to evaluate.
{% if user.is_logged_in %}
Welcome back, {{ user.name }}!
{% endif %}
else
Provides an alternative block of code to execute when an if
condition is false.
{% if condition %}
// code to execute if condition is true
{% else %}
// code to execute if condition is false
{% endif %}
{% if user.is_logged_in %}
Welcome back, {{ user.name }}!
{% else %}
Please log in.
{% endif %}
unless
The opposite of if
. Executes a block of code only if a condition is false.
{% unless condition %}
// code to execute if condition is false
{% endunless %}
The condition to evaluate.
{% unless user.is_logged_in %}
Please log in to continue.
{% endunless %}
Please log in to continue.
case
Executes one of many blocks of code, depending on the value of a variable.
{% case variable %}
{% when value1 %}
// code to execute if variable equals value1
{% when value2 %}
// code to execute if variable equals value2
{% else %}
// code to execute if variable doesn't match any values
{% endcase %}
The variable to evaluate.
{% assign level = "advanced" %}
{% case level %}
{% when "beginner" %}
Start with the basics
{% when "intermediate" %}
Build on your knowledge
{% when "advanced" %}
Tackle complex concepts
{% else %}
Select a level
{% endcase %}