Happening now | Office Hours: Customizing Your Theme With Dan-From-Ryviu | Ask your questions now!

How can I automatically display metafield key names in product details?

How can I automatically display metafield key names in product details?

eggplanted
Tourist
8 0 9

In our product details section, I am looking to display a tabulated list of product details using metafields, such as:

 

Color: Red

Material: Cotton

Fit: Slim

 

The usual way to do this is something like this:

 

Color: {{ product.metafields.custom.color.value }}
Material: {{ product.metafields.custom.material.value }}
Fit: {{ product.metafields.custom.fit.value }}

 

However, I want the list to be generated automatically by looping through metafields, i.e. avoiding the static text of  'Color', 'Material' and 'Fit' being static text. So in principle it would look something like this in pseudo-code:

 

FOR EACH METAFIELD IN A PRODUCT:
    {DISPLAY THE METAFIELD NAME}: {DISPLAY THE METAFIELD VALUE }
ENDFOR

However, I am struggling to find any syntax (in the documentation and through trial and error) that displays the key name of a metafield

 

Does such a thing exist?

 

If not, is there any workaround you can think up? We want to avoid any hard html-coding of product details like "Color: ", "Material: ", "Fit: " because it quickly becomes cumbersome in large product catalogs.

Replies 2 (2)

JE_eshop_jenny
Visitor
1 0 2

This what exacly what I wanna know too,  any developer can give a solid answer?

km9
Visitor
2 0 11

Here's one way you can do it. Basically, you iterate over the namespace of the metafields to get the key and value in an array, then assign variables to the first and last items in the array like so:

 

{% for metafield in product.metafields.namespace %}
  {% assign field_name = metafield | first | capitalize %}
  {% assign field_value = metafield | last %}
  <div>
    {{ field_name }}: {{ field_value }}
  </div>
{% endfor %}

 

Hope that helps!