skip to Main Content

I’m trying to add {{ product.variants.first.sku }} into a js file, the function is below

function buildPrice(data, onSale, priceVaries) {
  var priceHtml = '',
    onSaleClass = onSale ? ' price--on-sale' : '';
  var productSku = "{{ product.variants.first.sku }}";
  priceHtml += '<dl class="price' + onSaleClass + '" data-price>';
  priceHtml += '<div class="price__vendor">';
  priceHtml += '<dt>';
  priceHtml += '<span class="visually-hidden">' + bcSfFilterConfig.label.vendor + '</span>';
  priceHtml += '</dt>';
  priceHtml += '<dd>';
  priceHtml += data.vendor;
  priceHtml += '</dd>';
  priceHtml += '</div>';
  priceHtml += '<div class="product__sku">';
  priceHtml += '<dd>';
  priceHtml += productSku;
  priceHtml += '</dd>';
  priceHtml += '</div>';
  priceHtml += '<div class="price__regular card-price">';
  priceHtml += '<dt>';
  priceHtml += '<span class="visually-hidden visually-hidden--inline">' + bcSfFilterConfig.label.regular_price + '</span>';
  priceHtml += '</dt>';
  priceHtml += '<dd>';
  priceHtml += '<span class="price-item price-item--regular" data-regular-price>';

As you can see I tried using var productSku = "{{ product.variants.first.sku }}"; but it still just pastes {{ product.variants.first.sku }} in html instead of loading the sku number.

How can I get it to render the liquid insert instead of just pasting the code in visible html?

Would appreciate any help!

2

Answers


  1. I don’t think you need the json filter.

    product.variants.first.sku 
    

    That is a value. Makes no sense to filter it as json.

    Login or Signup to reply.
  2. You are not showing anything terribly dynamic in your sample– there’s nothing there that couldn’t be done with a snippet of liquid.

    However the way I go about blending shopify’s info with javascript is like:

    pricesnippet.liquid

    <script>
    var myObj = {
    product: {{product |json}},
    startingVariant : {{product.selected_or_first_available_variant | json }}
    };
    
    // now do something with product:
    (function(){
        myObj.product....
    
    })();
    </script>
    

    and then

    {% include 'pricesnippet' %} in your liquid where needed.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search