0
votes

I am attempting to write a simple code that inputs the string from a Shopify variant metafield into a div.

The challenge is that I know how to call the data in liquid, but I cannot call the data in a JS format. Every time I try to put the data into the code via liquid it doesn't come back.

Here is the code:

$('.single-option-selector').on('change', function(){
  let shipping_speed = {{ product.selected_or_first_available_variant.metafields.availability.type }}
  $('div.product-availability strong').html(shipping_speed);
});

How does one convert the liquid variable into a string that can be used in a JS file?

1
You need to wrap the value in quotes, eg. let shipping_seed = "{{ product... }}";Rory McCrossan

1 Answers

1
votes

You have a bit of a misunderstanding going on here. I will explain it to you, and you can adjust your code as needed.

Important Fact Liquid renders once. Shopify turns all Liquid into a gigantic HTML string and dumps it out, and the browser renders it. It is not dynamic.

So let us now assume you have a Metafield resource you attached to each variant. Since you are not rendering those values out at render time, you have no chance of showing your variant Metafield resources, when the customer changes a variant.

So the answer is for you is to create a Javascript data structure, and array of objects. Loop through your variants with Liquid. For each one, store the variant ID with the Metafield value in your Javascript array. You now have a nice reference to each variant value and the Metafield data you want.

In your Javascript event listener for variant changes, when a variant changes, examine your already created data structure, looking for the matching variant ID. When you find it, render the text that you saved from the Metafield value to go with it.

Bingo. You are a genius. Have fun.