contains operator not working on product collections

Guy10
Shopify Partner
6 0 1

Hi All,

Just getting started with Shopify/Liquid and loving it so far. Have come across an issue while testing some things out and was hoping someone here might be able to help. 

In product.liquid I have the following code:

 {% if product.collections contains 'Bossman' %}
      Bossman Product
    {% endif %}

All this should do is print the words 'Bossman Product' if the product is in the collection 'Bossman'. 

For some reason, this doesn't seem to work. Nothing shows on the product page even though it is in the collection. I can confirm this using:

{% for collection in product.collections %}
      {{ collection.title }}
  {% endfor %}

and getting 'Bossman' as the output. 

Sure its just something I'm missing but any help would be most appreciated.

Cheers,
Guy

Replies 8 (8)
Guy10
Shopify Partner
6 0 1

Update: I have managed to get output using:

{% for collection in product.collections %}
    {% if collection.title == 'Bossman' %}
      Bossman Product
    {% endif %}
  {% endfor %}

but surely the if statement should work alone?

Guy10
Shopify Partner
6 0 1

Update 2: Looking into it more, my previous post just answered my own question. Contains won't find objects within an array of objects. *facepalm*

HandHugs
Shopify Expert
175 1 48

This way would be easier on load times if you have a lot of collections:

 

{% assign productCollections = product.collections | join:',' %}
{% if productCollections contains 'Bossman' %}
// stuff here
{% endif %}
Thomas_Bartels
Shopify Partner
1 0 0
@HandHugs wrote:

This way would be easier on load times if you have a lot of collections:

 

{% assign productCollections = product.collections | join:',' %}
{% if productCollections contains 'Bossman' %}
// stuff here
{% endif %}

Take caution, this will also falsely match any collection containing the search string as a substring. Probably not the intended result.

stephdumais
Tourist
9 1 0
{% assign productCollections = product.collections | join:',' %}
{% if productCollections contains 'Bossman' %}
// stuff here
{% endif %}

I tried this myself but  productCollections only return CollectionDrop, so it never contains the string I specify. 

HandHugs
Shopify Expert
175 1 48
What template or snippet file are you using this code on?
stephdumais
Tourist
9 1 0

I used it in collection.liquid

All products for a tag are displayed but I want to exclude a collection from the results.

EXA-DEVs
Tourist
4 0 3

You have to do

{% assign productCollections = product.collections | map: 'title'%}
{% if productCollections contains 'Bossman' %} // stuff here {% endif %}