0
votes

In my Shopify theme I wish to display the value of a metafield. The key for this metafield is the string "prod_" joined with the product type.

Let's imagine that the product is a sofa. I can display the value of this metafield by simply using the metafield's name as a text string.

   {{product.metafields.global["prod__sofa"]}}

I however wish to replace the "sofa" part of the string with the value of the field.

To do this I can create a variable called "type"

   {% assign type = product.type %}

I am now however finding it difficult to use the variable "type" and the text string to look up the metafield.

My issue is in joining them together, I have used both a "+" and "&", but this does not work.

{{product.metafields.global["prod__" & type]}}
{{product.metafields.global["prod__" & type]}}

Am I joining the variable and string together incorrectly or is this simply not possible?

1

1 Answers

3
votes

This syntax is wrong {{product.metafields.global["prod__" & type]}}.

You can't concatenate strings that way.

You should generate the string before hand and use the ready string:

{% assign type = product.type | prepend: 'prod_' %}
{{product.metafields.global[type]}}

or

{%- capture type -%}type_{{product.type}}{%- endcapture -%}
{{product.metafields.global[type]}}