Dingo Bruce
Dingo Bruce

Reputation: 405

Shopify / Liquid specific loop index within loop

In Shopify I am trying to cycle through some metafields that contain feature titles. Then I need to cycle through some other metafields and get the feature description based on the current loop index.

This code works just fine for me, but it is very inelegant and I'm sure there is a much better way to achieve the same result!

{% for field in product.metafields.feature_title %}
    <h4>{{ field | last }}</h4>
    {% assign i = forloop.index %}
    {% if forloop.index == 1 %}
         <p>{{ product.metafields.feature_description.001 }}</p>
    {% endif %}
    {% if forloop.index == 2 %}
         <p>{{ product.metafields.feature_description.002 }}</p>
    {% endif %}
    {% if forloop.index == 3 %}
         <p>{{ product.metafields.feature_description.003 }}</p>
    {% endif %}
    {% if forloop.index == 4 %}
         <p>{{ product.metafields.feature_description.004 }}</p>
    {% endif %}
    {% if forloop.index == 5 %}
    <p>{{ product.metafields.feature_description.005 }}</p>
    {% endif %}
{% endfor %}

Additionally there is a flaw that this is limited to 5, or whoever many if statements creates.

Cheers,

DB

Upvotes: 0

Views: 3686

Answers (1)

bknights
bknights

Reputation: 15367

not tested but something like this should work:

{% for field in product.metafields.feature_title %}
  <h4>{{ field | last }}</h4>
  {% capture idx %}00{{forloop.index}}{% endcapture %}
  {% assign key = idx | slice: -3, 3 %}
  <p>{{ product.metafields.feature_description[key]}}</p>
{% endfor %}

Upvotes: 1

Related Questions