简体   繁体   中英

Shopify Liquid - pass selected values from liquid to js

I'm trying to create a page that displays all the products of my shop and when the user clicks on two or three products they can see a table at the end of the page with all the products characteristic side by side.

I have little experience in liquid programming and I understand the basics but not much more.

So far I managed to display all of my products in a page and when the user clicks on some of them a table appears in the bottom of the page, my problem right now is:

How can I pass the selected items between the.liquid and the.js files? Or is there a simpler way to catch the selected items and display their characteristics?

Here is the code to display the products in the.liquid file:

<div class="collection-uomo">
    <div class="compare-products">
        <h3>MAN</h3>
        {% assign counterUomo = 0 %}
        {% for product in collections.all.products %}
            {% for collection in product.collections %}
                {% if collection.title == 'MAN' %} 
                    <div class="compare-product" data-id="{{ counterUomo }}">
                        <img src="{{ product.featured_image | product_img_url: 'medium' }}" title="{{ product.title | escape  }}"/>
                        <h6 class="product-title">{{ product.title | escape  }}</h6>
                    </div>
                    {% capture counterUomo %}{{ counterUomo | plus:1 }}{% endcapture %}
                {% endif %}
            {% endfor %}
        {% endfor %}
    </div>
</div>

My idea was to use the data-id to identify the product but I don't know how to do so with liquid. Thank you in advance to anyone who helps.

The question leads to many possible answer. A general approach is to save everything you need in HTML. Something like this

{% for product in collection['MAN'].products %}
  <div class='product-preview' data-id="{{product.id}}" data-thumbnail="{{product.image | img_url: '400x'}}" data-title="{{product.title}}">
    ...
  </div>
{% endfor %}
<script>
$(".product-preview").on("click", ...);
</script>

Or

{% for product in collection['MAN'].products %}
  <div class='product-preview' onClick="addProduct('{{product.id}}','{{product.image | img_url: '400x'}}','{{product.title}}')">
    ...
  </div>
{% endfor %}
<script>
function addProduct(productId, thumbnail, title){
 return function(){...}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM