Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Statement With Contains And Downcase In Liquid

Tags:

shopify

liquid

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.

like image 573
Cory Dee Avatar asked Mar 06 '23 14:03

Cory Dee


1 Answers

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.

like image 149
Dave B Avatar answered Mar 12 '23 15:03

Dave B