8

I'm attempting to use downcase inside of an if statement, while using the contains criteria. I can't believe there isn't a Google-able solution.

Here is what I've tried so far:

{% if collection.tags | downcase contains "womens" %}
{% if {{collection.tags | downcase}} contains "womens" %}
{% if {{collection.tags}} | downcase contains "womens" %}

I'd like to not have to loop the array and assign the downcased strings back into a new array if possible, just to keep things clean and efficient.

1 Answer 1

13

You can't manipulate values inside of an if statement in Liquid - you'll need to assign the downcased values to a variable, then use that.

So in your case, something like:

{% assign collection_tags = collection.tags | join: '~~~' | downcase | split: '~~~' %}
{% if collection_tags contains 'womens' %}

Note:

downcase is a string operation, not an array operation, so the above code uses join to turn the array into a single long string with some delimiter that shouldn't appear in any of your tags, then split-ing that string back into an array using the same delimiter after changing the case.

If we just use downcase on the array itself, Shopify will implicitly join the array using an empty string, and your contains statement would then be looking for the substring womens in the resulting blob. For contrast, when using contains on an array, Shopify will only match a tag that is an exact-match of your search term.

To illustrate, if your collection tags are ['Not-For-Women','Stuff'], downcase-ing the array directly will give you the string 'not-for-womenstuff', which happens to contain the substring 'womens' and would be an unexpected false-positive.

4
  • 1
    As an addendum, Liquid braces are never nested - {% if x == {{ variable }} %} is never used, the correct syntax is always {% if x == variable %} :)
    – Dave B
    Commented Aug 24, 2018 at 16:31
  • This worked perfectly, and the explanations were helpful. Thanks @Dave B
    – Cory Dee
    Commented Sep 13, 2018 at 18:27
  • @DaveB Thank you for your answer it worked for me!!! I was wonderign, im new to Liquid and trying to figure out some syntax. can the assign be put into If somehtign like this{% if collection.tags | join: '~~~' | downcase | split: '~~~' contains 'womens' %}
    – knowzero
    Commented Dec 30, 2022 at 17:52
  • @knowzero: No, the if statements need to be simple comparisons in Liquid. You would need to assign a variable to the tag array before the if statement and then use that. :)
    – Dave B
    Commented Jan 9, 2023 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.