简体   繁体   中英

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

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 %}

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