Mike
Mike

Reputation: 638

Liquid control flow tags {% for %} and {% else %}

Still new to using liquid in Shopify themes, and documentation is lacking in a few areas, so I'm in "learn as you go" mode, and I'm rebuilding Shopify's Simple theme from scratch as a learning tool. I cam across this bit of code in collection-template.liquid:

1   {% for product in collection.products %}
2       {% if collection.products.size == 1 %}
3           <!-- Template Logic -->
4       {% else %}
5           <!-- Template Logic -->
6       {% endif %}
7           
8       {% include 'product-grid-item' %}
9
10  {% else %} <!-- HANGING ELSE STATEMENT? -->
11
12      <!-- Template Logic -->
13
14      {% if shop.products_count == 0 and collection.handle == 'all' %}
15          <!-- Template Logic -->
16      {% else %}
17          <!-- Template Logic -->
18      {% endif %}
19  {% endfor %}

Coming from a Java background, line 10 looks like a compile error. It's an else statement with no opening if.

But, based on context clues, I'm wondering if that {% else %} is like an if (empty), which would mean the above snippet would be functionally equivalent to:

{% if collection.products.size == 0 %}
    <!-- Line 11-18 from above snippet -->
{% else %}
    {% for product in collection.products %}
        <!-- Line 2-9 from above snippet -->
    {% endfor %}
{% endif %}

Can someone confirm this?

Upvotes: 1

Views: 1702

Answers (1)

bknights
bknights

Reputation: 15437

It's a fallback for the case where the collection used by the for loop has zero length. See https://help.shopify.com/themes/liquid/tags/iteration-tags#else

Upvotes: 3

Related Questions