Ad

Assigning Liquid To Javascript Variable

- 1 answer

var first = 'one',
    second = 'two.png';
    image = first + second;
console.log('js image: ' + image);
image = '{{ image | asset_url }}';
console.log('liquid image: ' + image);

Produces in the console:

js image: onetwo.png
liquid image: 

I cannot get the code to output the code from the liquid filter. I have tried using {% raw %} and looked at a few SO questions (Shopify: Using variables from {% schema %} in Javascript, Using javascript variables in Shopify liquid, Using asset_url within a .js.liquid file) to no avail.

What am I doing wrong here? I am expecting to get:

liquid image: onetwo.png?123456789

Even removing asset_url:

image = '{{ image }}';

Still produces:

liquid image:
Ad

Answer

After chatting with @Subhrajyoti Das there is a hacky way of doing it.

Create the full string with dummy text where the actual filename is:

assetString = '{{ 'filename' | asset_url }}'

This produces:

cdn.shopify.com/s/files/0/0000/0000/0000/t/00/assets/filename?0000000000

Then use string replacement to replace 'filename' with the asset variable:

image = assetString.replace("filename", image);
Ad
source: stackoverflow.com
Ad