Search code examples
shopifyliquidshopify-template

Keeping the code readable in my liquid tags list snippet


I have some code to filter out the display of certain tags on my shopify product page template. It reads in this comma separated list of tags I want to exclude from display on the product page:

{% assign exclude_tags = "Dangerous Goods,Quick Links,ShippingLetter,ShippingParcel" | split: ',' %}

And the product page reads in that snippet:

{% include "excluded-tags" %}

...and excludes tags from being displayed if they are found in the exclude_tags list:

{%- for tag in product.tags -%}
{% if exclude_tags contains tag %}
{% continue %}
{% endif %}

And that all works perfectly fine. However, this list of tags to exclude is going to end up quite large (lets say there might be 100 tags here!!), and I want to keep it readable for later editing etc, so I tried changing the comma separated list to one item per line in the code editor, but it stops working when I do that? Items that should be hidden on the product page are not hidden doing it that way.

Is there a way to achieve this instead of having the comma separated values all on a single line of code, something that looks like this:

{% assign exclude_tags = "Dangerous Goods,
Quick Links,
ShippingLetter,
ShippingParcel" | split: ',' %}

Cheers, Rob


Solution

  • You can use capture to assign multiline text to a Liquid variable and then use split to convert it to Array.

    {% capture exclude_tags %}
      Dangerous Goods,
      Quick Links,
      ShippingLetter,
      ShippingParcel
    {% endcapture %}
        
    {% assign exclude_tags = exclude_tags | split: ',' %}
    

    However, as per you above code snippet, you don't need to use split. You can use contains with a string. So your code will become just this

    {% capture exclude_tags %}
      Dangerous Goods,
      Quick Links,
      ShippingLetter,
      ShippingParcel
    {% endcapture %}