if contain in shopify liquid

If Contain in Shopify Liquid

If you are working with Shopify Liquid code, you may come across the need to check if a certain value exists in a variable. In Liquid, you can use the "contains" operator to check if a value is present in a string or array.

Using the "contains" operator

The "contains" operator checks if a specific value exists in a string or array in Shopify Liquid. It returns "true" if the value is present and "false" if it is not. Here is an example:


{% assign my_array = "apples, bananas, oranges" | split: ", " %}
{% if my_array contains "bananas" %}
  <p>I love bananas!</p>
{% endif %}

In this code snippet, we first create an array called "my_array" by using the "split" filter to separate the string "apples, bananas, oranges" into separate values. We then use the "contains" operator to check if the array contains the value "bananas". If it does, we output the message "I love bananas!".

Using the "unless" operator

You can also use the "unless" operator in combination with "contains" to check if a value is not present in a string or array. Here is an example:


{% assign my_string = "Hello, World!" %}
{% unless my_string contains "Goodbye" %}
  <p>Hello forever!</p>
{% endunless %}

In this code snippet, we create a string called "my_string". We then use the "unless" operator in combination with "contains" to check if the string does not contain the value "Goodbye". If it does not, we output the message "Hello forever!".

Using the "unless" operator with arrays

You can also use the "unless" operator in combination with arrays to check if a value is not present in an array. Here is an example:


{% assign my_array = "apples, bananas, oranges" | split: ", " %}
{% unless my_array contains "kiwis" %}
  <p>No kiwis for me!</p>
{% endunless %}

In this code snippet, we create an array called "my_array". We then use the "unless" operator in combination with "contains" to check if the array does not contain the value "kiwis". If it does not, we output the message "No kiwis for me!".

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe