skip to Main Content

I’m creating a custom Shopify section to display product specifications using a metafield. My metafield named specs is set as an entry list, with each entry containing arrays for label and description. I want to loop through these arrays and render each label-description pair in a list or table format.

Here’s my current Liquid code:

{% assign specs_list = product.metafields.custom.specs.value %}

<ul>
  {% for spec in specs_list %}
    <li>
      <span>{{ spec.label }}</span>
    </li>
    <li>
      <span>{{ spec.description }}</span>
    </li>
  {% endfor %}
</ul>

Result:

["Label 1","Label 2","Label 3","Label 4","Label 5"]
["Valeur 1","Valeur 2","Valeur 3","Valeur 4","Valeur 5"]

However, spec.label and spec.description aren’t displaying the way I need, likely due to being detected as arrays within each entry.

Attempts so far: Despite trying various approaches to iterate through the arrays using nested loops, the current code version is the only one that works.

Expected Output: I want to display each label-description pair like this:

Label 1 | Value 1

Label 2 | Value 2

Label 3 | Value 3

2

Answers


  1. I think this will work:

    {% assign labels_raw = product.metafields.custom.specs.labels %}
    {% assign values_raw = product.metafields.custom.specs.values %}
    
    {% comment %} Formatting the labels {% endcomment %}
    {% assign labels_temp1 = labels_raw | remove: '[' %}
    {% assign labels_temp2 = labels_temp1 | remove: ']' %}
    {% assign labels_temp3 = labels_temp2 | remove: '"' %}
    {% assign formatted_labels = labels_temp3 | split: ',' %}
    
    {% comment %} Formatting the Values {% endcomment %}
    {% assign values_temp1 = values_raw | remove: '[' %}
    {% assign values_temp2 = values_temp1 | remove: ']' %}
    {% assign values_temp3 = values_temp2 | remove: '"' %}
    {% assign formatted_values = values_temp3 | split: ',' %}
    
    <ul>
      {% for label in formatted_labels %}
        {% assign index = forloop.index0 %}
        <li>
          <span>{{ label | strip }}</span> &nbsp;|&nbsp; <span>{{ formatted_values[index] | strip }}</span>
        </li>
      {% endfor %}
    </ul>
    

    However just wrote this in vsCode, I haven’t tested it out.
    Let me know if it works or not.

    Login or Signup to reply.
  2. As your elems content in the list is formatted as an array you may outpout values as it:

    {% for label in labels %}
        {{ label.first }} {{ label.last }}
    {% endfor %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search