Shopify, return product tags except certain prefixed tags, in Javascript

Viewed 135

New to Shopify and Liquid (enjoying it). Not greatly experienced with JS! We have Shopify site that uses product tags for the chocolates in various chocolate boxes. The theme is not compatible with collection filtering and is setup to use tags for this also. Thus the tags now contain "Price £10 - £20" etc.

I have code on the product page that loops over all product tags and renders a snippet unless the tag contains 'price':

{% for tag in product.tags %}
  {% unless tag contains 'Price' %}
    <li>{% render 'chocolate-menu' with tag as tag %}</li>
  {% endunless %}
{% endfor %}

All good and easy (with StackOverflow help). However, on the collection pages the 'quickview' option (which launches a popup) inserts a list of the chocolates (tags) via javascript:

var chocolatesMenu = product.tags;
var chocolatesMenuSpaced = chocolatesMenu.join(', ');
quickview.find(".proBoxInfo .quickViewSKU").append("<label>Chocolates:</label> " + chocolatesMenuSpaced);

How can I 'scrub' the price-related tags from product.tags in js? Or is there a clever liquid and js way to do this? I just want to list all tags that don't start with 'Price'.

1 Answers

To do that in Javascript you can filter the Price value, as you're doing in liquid.

var chocolatesMenu = "{{ product.tags }}".split(",").filter((tag)=> tag.indexOf("Price")<0);
// OR if you somehow have already product.tags in Javascript
// var chocolatesMenu = product.tags.filter((tag)=> tag.indexOf("Price")<0);
var chocolatesMenuSpaced = chocolatesMenu.join(', ');
quickview.find(".proBoxInfo .quickViewSKU").append("<label>Chocolates:</label> " + chocolatesMenuSpaced);


But my suggestion is: don't.

What happens if one day, you need one more tag for a different topic? Are you going to modify all the places where you filtered out "Price" and add "newTag"?

You should be using metafields. If you're theme is not compatibile with metafields, maybe find a better one.

In alternative what you can do is using tag prefixes.

So instead of having white,dark,milk,Price 10 you should have kind:white,kind:dark,kind:milk,price:Price 10 and you always filter by kind or price or whataver.

Related