Search code examples
shopifyshopify-template

Loading Shopify Product Metafields in snippets


I am trying to edit the default "Dawn" theme in my shopify store. My aim is to output product meta fields through a snippet. To do that, I have created a snippet called "color-swatches.liquid" which has the following code:

    <div class="sw-external-links modification">
        {%- if product.metafields.my_fields.current_product_color -%}
    </div>

When calling this snippet from product-card.liquid, I use the following liquid code:

{% render 'color-swatches', product: product_card_product %}

But I am not able to output the value of current_product_color metafield inside product.

If I paste the snipped code directly in product-card.liquid like this, it works:

{{ product_card_product.metafields.my_fields.current_product_color }}

Can you please tell me what am I doing wrong? I just want the snippet code to output the current_product_color metafield when I pass the product_card_product variable to it.


Solution

  • Although there is not enough information in your question, I will try to help you the best I can.

    1. In the snippet file (color-swatches.liquid), check if you're using the correct variable when accessing the product's metafield.
      If you render your snippet (in 'product-card.liquid') like this:
      {% render 'color-swatches', MY_PRODUCT: product_card_product %},

      Then you should access the metafield (in 'color-swatches.liquid') like this:
      {{ MY_PRODUCT.metafields.my_fields.current_product_color }}

    2. Check that if statement.

      • In liquid, prefer the != blank syntax:
        {%- if product.metafields.my_fields.current_product_color != blank -%}
      • Check if the if statement even works.
        For that try to render the snippet outside the if.
    3. If nothing is working double check yourself everywhere.
      Do this using <script>console.log({{ YOUR_LIQUID_CODE | json }})</script> and check the browser's console to see the logs.
      In both files, check the metafield, and the product.