case
Creates a switch statement that will cause a specific portion of code to run when the evaluated case matches the expected value. case
are usually recommended due to how easier to read they are especially when when dealing with nested if
statements.
This statement is a two parter:
case
: To initialize the switch statement.when
: To match a condition.
liquid
{% case variable %}
{% when first_value %}
first_block
{% when second_value %}
second_block
{% else %}
third_block
{% endcase %}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
variable
: The variable we want to base our statement upon.first_value | second_value
: Certain values we want to match.first_block
: Rendered expression whenfirst_value
matches the value ofvariable
.second_block
: Rendered expression whensecond_value
matches the value ofvariable
.third_block
: Rendered expression where no previous conditions were met.
Example
Data
json
{
"product": {
"slug": "youcan"
}
}
1
2
3
4
5
2
3
4
5
Note: Data is only refereed as a reference for this example and is in no means reflecting real world data.
liquid
{% case product.slug %}
{% when 'product-1' %}
This is product one
{% when 'youcan' %}
This is YouCan
{% else %}
This is an unknown product
{% endcase %}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Output
This is YouCan