(Liquid) Checking for a variable in an array

970 Views Asked by At

I’m looking to find if the title of the current collection page exists inside the array of shop.vendors and display a div only if the collection page title does not exist in the array. From the documentation it seems like I should be able to do this but it doesn't work?

{%- unless shop.vendors contains collection.title -%}
 <div> display content in here if condition is not met </div>
{%- endunless -%}
2

There are 2 best solutions below

5
Mandasa Technologies On

You can rewrite your code as:

{% for vendor in shop.vendors %}
  {% if vendor == collection.title %}
     <div> display content in here if condition is not met </div>    
  {% endif %}
{% endfor %}
0
David Ferguson On

So I've found out why this wasn't working, for anyone else who comes across this

shop.vendors renders an ampersand as &amp rather than &, while collection.title renders it as &. Therefore, if you try to compare the names it won't work.

The solution is doing | escape to only shop.vendors so they're formatted the same, then the comparison will work. I also did | remove to get rid of the ampersand entirely as it's not strictly needed in the name comparison in my case.