Updating DOM Elements With Metadata Field Values On Variant Change

- 1 answer

Using Slate framework.

I know there are quite a few topics touching on this but I've not yet found anything that seems to work for me.

I'm using Accentuate metafields plugin to create custom defined metafields. These are indeed easily accessible within my template in Liquid; for example:

{% for variant in product.variants %}
  <p data-variant-ingredients >{{ variant.metafields.product_info.product_ingredients }}</p>
{% endfor %}

However, these variant metafields do not seem to be accessible via Javascript on the backend and it's preventing me from making an AJAX call to update the appropriate DOM elements via an event listener.

I feel like I've wasted hours trying to solve this to no avail — perhaps I'm just overthinking it but I've hit a wall.

Many thanks!


Part of the issue here was my misunderstanding of where things are rendered. Nonetheless, I scrolled right past by all rights would have helped in the Shopify documentation:

var content = {{ | json }};

It doesn't seem clear to me how this is used other than it turns it into "JSON." Thanks to Dave, I know know I can declare a JS variable anywhere in my liquid files and effectively toss this up to be accessible within my theme's javascript files!

Hope this helps someone else down the line!



You need to get a firm grip on the Shopify terminology, in this case client-side JS vs. server rendering of Liquid.

Liquid is rendered server side. Metafields are therefore rendered server side too. Therefore when you render your Liquid, you can render it as you need it, including into some form of a Javascript data structure for use client side. Bingo!

Javascript is rendered client side. Hence if you rendered some Liquid data (server side) into some Javascript variables, you can happily play games with your DOM elements and event listeners.

example: from any product.liquid

   var fumbleDoof = {{ product | json }};

Note that this pattern is as old as the hills and works a peach, so hopefully your wall is now much smaller, and you can move on to more challenging tasks! You can access all the glory of the product in Javascript by accessing the variable fumbleDoof. Same goes for metafields, etc. etc. etc.