Ad

How To Access Shopify API In Liquid Or Javascript Variables In Liquid?

- 1 answer

From what I can find, it seems that this may be impossible. There must be someway to do this though. All I want to do is get some information from the API, and pass it to a liquid variable. Maybe there's another way.

Ad

Answer

Since liquid renders server side you can't pass javascript variables into the template engine. However you can embed liquid template code in javascript functions. There's a post on the shopify forums with some example code that may help: Pass variable from Java script to liquid?

for example:

 $(function() {
  new Shopify.OptionSelectors("product-select", { product: {{ product | json }}, onVariantSelected: selectCallback });

  // Add label if only one product option and it isn't 'Title'.
  {% if product.options.size == 1 and product.options.first != 'Title' %}
  $('.selector-wrapper:eq(0)').prepend('<label>{{ product.options.first }}</label>');
  {% endif %}

  // Auto-select first available variant on page load.
  {% assign found_one_in_stock = false %}
  {% for variant in product.variants %}
    {% if variant.available and found_one_in_stock == false %}
      {% assign found_one_in_stock = true %}
      {% for option in product.options %}
        $('.single-option-selector:eq({{ forloop.index0 }})').val({{ variant.options[forloop.index0] | json }}).trigger('change');
      {% endfor %}
    {% endif %}
  {% endfor %}

});
Ad
source: stackoverflow.com
Ad