Loop through a metaobject's metafields in Shopify/Liquid

2.8k Views Asked by At

I am trying to loop through a metaobject's metafields in Shopify/Liquid without knowing the specific metafield keys, but can't seem to figure it out. I've successfully grabbed the metaobject, in this case it's referenced on a product via a metafield. And I can access the stored metafield value(s) directly referencing the metafield key and values syntax. My issue is that I would like to be able to add fields to the metaobject definition down the road, and have them dynamically added in the theme, without having to go into the theme file.

This works just fine, as long as I know the metaobject's metafield key(s):

{% assign my_metaobject =  product.metafields.custom.my_metaobject.value %} 

{{ my_metaobject.a_known_key.value }}

What I would like to do is something like this:

{% assign my_metaobject =  product.metafields.custom.my_metaobject.value %}

{% for unknown_field in my_metaobject.metafields %} //Loop over every metafield in the metaobject

    {{ unknown_field.value }}

{% endfor %}

Obviously the latter doesn't work, but there must be a way to do that... right?

1

There are 1 best solutions below

2
On

It is nothing but playing with key:value storage. One simple solution is to save your keys as JSON, and then you have a dynamic keys structure when you need it. Store them in a known place, aa known metafield. Boom. You need never wonder what the keys you need are, just read them, and open up whatever other resource objects they may point to.