Search code examples
shopifyliquidshopify-template

Shopify: Hide size variant heading in liquid template when there are no sizes defined


I am using Shopify and I would like to hide the size variant title in my template when there is no size defined for a product.

Here is a screen shot of what the rendered code looks like on my store.

enter image description here

Here is a code snippet from my liquid template:

<div class="options clear">
{% if product.available %}
<div class="product-info-row">
  <div class="product-info-col1">
    <h4>Quantity</h4>
    <div class="quantity">
      <div class="quantity-display">1</div>
      <input name="quantity" type="hidden" value="1" data-max="{{product.selected_or_first_available_variant.inventory_quantity}}">
      <div class="quantity-decrement">-</div>
      <div class="quantity-increment">+</div>
    </div>
  </div>
  {% if product.variants.size >= 1 %}
  <div class="product-info-col2">
    <h4>Size</h4>
    <div class="variants">
      {% unless product.selected_or_first_available_variant.title contains "Default" %}
      <ul class="variant-list">
        {% for variant in product.variants %}
        {% if variant.available %}
        <li class="{% if variant == product.selected_or_first_available_variant %} selected{% endif %}" data-value="{{ variant.id }}" data-quantity="{{ variant.inventory_quantity }}"> {{ variant.title }}</li>
        {% endif %}
        {% endfor %}
      </ul>
      {% endunless %}
    </div>
  </div>
  {% endif %}
  <input type="hidden" class="variant-id" name="id" value="{{product.selected_or_first_available_variant.id}}">
</div>
{% endif %}

I am a bit confused because there is already operator logic around the HTML for the size variant: {% if product.variants.size >= 1 %}. This product has no variants for size defined (0 is less than 1), so, why is this block of HTML for the size variant still showing? Any help would be much appreciated. Thank you!


Solution

  • Each product in Shopify contains at least one variant. Your condition {% if product.variants.size >= 1 %} is true. But {% unless product.selected_or_first_available_variant.title contains "Default" %} is false.

    For a better understanding of product object, I want to suggest you add {{ product | json }} to your liquid to render all object as serialized JSON. It will give you better understanding about product object and his fields