Search code examples
htmlshopifyliquidshopify-template

How to loop through the metafields in liquid


I need to loop the metafields for the image part where the metafields keys are:additional_info_icon_1, additional_info_icon_2 and additional_info_icon_3.

<div class="addition-info--content">
 <div class="addition-info-img">
  <img src="{{ product.metafields.global.additional_info_icon_1.value | img_url: 'master' }}">
 </div>

 <div class="addition-info-img">
  <img src="{{ product.metafields.global.additional_info_icon_2.value | img_url: 'master' }}">
 </div>

 <div class="addition-info-img">
  <img src="{{ product.metafields.global.additional_info_icon_3.value | img_url: 'master' }}">
 </div>
</div>

Solution

  • Your array containing all your metafield values is

    product.metafields.global
    

    So you need to extract the keys held in the global namespace that you are interested in. Note that due to poor choices, your keys are lumped into the global namespace, making the selection of keys much harder than it has to be.

    Anyway

    {% for key in product.metafields.global %}
    

    will give you all the keys in that global namespace.

    Now you have to figure out if your key is interesting or not. If it contains the string "additional_info_icon_" then you know it might be interesting. So now you would act with that key, to get the value stored at that key, and output that in your Liquid.

    I may be forgetting, but I think key[0] is the key and key[1] is the value. Try that, and see where further research takes you.