How to Render Product Swatches on Collection Page Using Shopify Liquid

How to Render Product Swatches on Collection Page Using Shopify Liquid

Displaying product swatches on the collection page enhances the user experience by allowing customers to preview available variants without navigating to the product page. Here’s how to implement it using Shopify Liquid.

1. Loop Through Product Variants

Modify your collection.liquid or the relevant section that renders products:

{% for product in collection.products %}
  <div class="product-item">
    <a href="{{ product.url }}">
      <img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">
    </a>
    <h3>{{ product.title }}</h3>
    
    <div class="swatches">
      {% for variant in product.variants %}
        {% if variant.option1 %}  
          <span class="swatch" style="background-color: {{ variant.option1 | handle }}"
                title="{{ variant.option1 }}"></span>
        {% endif %}
      {% endfor %}
    </div>
  </div>
{% endfor %}

2. Style the Swatches with CSS

.swatches {
  display: flex;
  gap: 5px;
  margin-top: 5px;
}

.swatch {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: inline-block;
  cursor: pointer;
  border: 1px solid #ddd;
}

3. Ensure Swatch Colors Match Variant Names

If your color names do not match CSS color values, use a mapping technique in Shopify Liquid or JavaScript to ensure the correct swatch colors are displayed.

{% assign color_map = "Red:#ff0000,Blue:#0000ff,Green:#008000" | split: "," %}
{% for color in color_map %}
  {% assign pair = color | split: ":" %}
  {% if variant.option1 == pair[0] %}
    <span class="swatch" style="background-color: {{ pair[1] }}"></span>
  {% endif %}
{% endfor %}

Conclusion

This method dynamically displays product swatches on the collection page, improving the visual shopping experience. Further enhancements can include interactive hover effects or variant selection via JavaScript for even better UX.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top