skip to Main Content

I’m using Shopify and I need to show some message if specific product tag is exist. I need to check for product tags from JS file and need to know how can I do that.

I tried to use {{product.tags}} in the js file but I got an error, I also tried that in .js.liquid file and it still throw an error.

{% assign clearance = false %}
    {% for tag in product.tags %}
            {% if tag contains 'Clearance' %}
                 {% assign clearance = true %}
            {% endif %}
   {% endfor %}

There is a way that I could use that in js? If not, how can I grab all product tags in js way? I know I can do that from liquid file but I have to do that only in the js file.

2

Answers


  1. You are probably looking for an extension to Javascript called jsx.

    Aside from that, natively, you have template literals, but you can only use expressions in that, no looping or other logic (aside from ternary expressions).

    If what you are looking for is not related to creating HTML, but only to modifying a variable (or executing other code on data), you can use standard Javascript:

    let clearance = false;
    for (const tag in product.tags) { // this assumes product.tags is an object
    for (const tag of product.tags) { // this assumes product.tags is an array
        if (tag.includes('Clearance') {
            clearance = true;
        }
    }
    
    Login or Signup to reply.
  2. The .js.liquid file will only accept translation string as var in Liquid (example: {{ “my_text” | t }}.

    If you want to use other kind of Liquid strings in Javascript code, you may use a section and include your javascript inside {% javascript %} tags.

    This will also work in a snippet or a template.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search