How to use Case-When Statement in Liquid Shopify

How to use Case-When Statement in Liquid Shopify

What is case-when Statement in Liquid Shopify?

Case-when generates a switch statement to compare the values of two variables. The switch statement is initialized by case, and its values are compared by when.

case-when Syntax

{% case variable %}
  {% when first_value %}
    first_expression
  {% when second_value %}
    second_expression
  {% else %}
    third_expression
{% endcase %}

Real World Example

Let’s say, We want to display a specific product based on the article handle. For it, we can use a case-when statement. We need to implement this code in the Sections -> main-article.liquid file.

{% assign article_handle = article.handle %}
{% assign product_handle = '' %}
{% case article_handle  %}
  {% when 'cleanser' %}
    {% assign product_handle = 'cleanser' %}
  {% when 'serum' %}
    {% assign product_handle = 'serum' %}
  {% else %}
    {% assign product_handle = 'fair' %}
{% endcase %}

{% assign product = all_products[product_handle] %}

In our example, if our article handle equals cleanser then the product_handle value will be cleanser. if our article handle equals serum then the product_handle value will be serum. if our article handle does not match any of these two value then the product_handle value will be fair.

You might also Like: How to display only products in search results Liquid Shopify

Hardik Davra
Hardik Davra
Hardik Davra is a CEO at Candisoft Tech, a Company specializing in Shopify Development. I have over 5 years of experience in Shopify website development.

Leave a Reply

Your email address will not be published. Required fields are marked *