banjax
banjax

Reputation: 37

Reading all products' tags in a FOR loop with a Shopify theme app extension. Can it be done?

I am working on a Shopify app that uses a theme app extension to alter how the price is displayed based on the tags associated with that product. The following code achieves this effect on product pages by inserting these lines of liquid in the price . The if statement looks for a match on the product tags and displays either my code when there is a match or the straight price when there is not.

var x = document.querySelectorAll(".product-single__price");
var i;
for (i=0; i < x.length; i++) {
    x[i].innerHTML = `
      {%- if product.tags contains 'mytags' -%}
        {% comment %} mycode {% endcomment %}
      {%- else -%}
        {{ product.price | money | strip_html }}
      {%- endif -%}
    `;
}

 

However, I cannot get this to work on collection pages. I'm assuming this is because the theme app extension's injection is occurring after the loop that displays the product grid and the product tags are no longer readable. Even if I assign the last product on the collection page with the tag to match, it doesn't display my code.

Is there a work around where I can pull the tags for each product and inject this code to each in the grid/list?

Upvotes: 0

Views: 295

Answers (1)

David Lazar
David Lazar

Reputation: 11427

You should render all products in a collection into a Javascript data structure, because as you well know, Liquid renders first, creating a giant string of HTML. Inside this HTML Shopify is injecting your Liquid too in your Theme App Extension. So far so good?

Once the Liquid has been totally rendered, that is, the entire collection up to the limits of pagination are in the DOM would any Javascript execute. So it is at this point that you could iterate the DOM for rendered products, and use it. So you could do your querySelector on product prices, and do your logic based on the data you previously saved.

If you expect to be able to change prices on the fly in the Liquid phase, your logic has to be moved from JS to Liquid itself. In other words, when rendering a single product in the collection template, you alter the price then and there, based on logic you have at your disposal, like a tag or metafield.

Upvotes: 0

Related Questions