Conditional Statements - Extended

After learning the basics of conditional statements, we explore methods that extend our conditional checking. The contains operator is used to check a string in within a string. 

{% assign city_state = "Phoenix, Arizona" %}
{% if city_state contains "Arizona" %}
  Welcome to Arizona!
{% endif %}

To remove the case sensitivity, lowercase both strings. Use the downcase filter (we'll learn more about filters soon) when needed.

{% assign city_state = "Phoenix, Arizona" | downcase %}
{% if city_state contains "arizona" %}
  Welcome to Arizona!
{% endif %}

You can use contains to search items within an array of strings.

<!-- school_days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] -->
{% assign current_day = "Monday" %}
{% if school_days contains current_day %}
  It's a school day.
{% endif %}

Another helpful method is the unless operator. This operator runs code when a statement is false.

<!-- school_days: ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] -->
{% assign current_day = "Saturday" %}
{% unless school_days contains current_day %}
  It's the weekend!
{% endunless %}

There is a similarity to the != operator. Where the ! negates the equal sign.

{% if 1 != 2 %}
  This works!
{% endif %}

{% unless 1 == 2 %}
  Or this works!
{% endunless %}

Finally, we'll end with the switch statement, which you can think of as many "if this equals" statements. Instead of adding numerous if statements to check a variable equals another, you can just use one "case/when" statement.

Instead of this:

{% assign current_weather = "sunny" %}

{% if current_weather == "rainy" %}
  It's spring.
{% endif %}

{% if current_weather == "cold" %}
  It's fall.
{% endif %}

{% if current_weather == "snowy" %}
  It's winter.
{% endif %}

{% if current_weather == "sunny" %}
  It's summer!
{% endif %}

Replace it with this:

{% assign current_weather = "sunny" %}
{% case current_weather %}
  {% when "rainy" %}
    It's spring.
  {% when "cold" %}
    It's fall.
  {% when "snowy" %}
    It's winter.
  {% when "sunny" %}
    It's summer!
  {% else %}
    I'm not sure what season it is.
{% endcase %}

First you start the case with the variable you want to compare to. Then each when statement compares it to the case variable. At the end of this switch statement, there is an else condition which is shown if the variable doesn't match any other condition. The else condition is optional and you don't need to add it.

Joe Pichardo | Shopify Developer

About Joe Pichardo

Joe Pichardo is a Shopify Developer creating themes and apps to help other programmers succeed on the ecommerce platform.

Having trouble? Ask for help.