Ad

Accessing Shopify Liquid Variables In Javascript

- 1 answer

My question is, is it possible to do access the variables in Shopify Liquid using Javascript?

{% assign my_array= "apples, oranges, peaches, tomatoes" | split: ", " %}


function my_function(number){
    return "{{my_array[number]}}";
  }

  $('#click_me').click(function(){
    alert(my_function(0));
  });

I know this is possible with AJAX and PHP, but is there a similar way I can implement using Shopify Liquid and JQuery alone?

Ad

Answer

Liquid is a back-end tempalting language, this means that it's rendered before the Javascript. It means that once the liquid rendering is done you won't have access to the liquid logic and since the JS is rendered AFTER the liquid it means that you can't access it at all.

So you can't pass JS variables to liquid in real time.

But you can create a JS object with liquid:

{% assign my_array= "apples, oranges, peaches, tomatoes" | split: ", " %}

var my_array = {{ my_array | json }};
function my_function(number){
  return "my_array[number]";
}

$('#click_me').click(function(){
  alert(my_function(0));
});

You can use AJAX to get specific page, but from your example this will do you no good, since you are trying to access a liquid variable on a Javascript event, which is not possible.

Ad
source: stackoverflow.com
Ad