Re: {{ product | json }} not working in a .js file?

{{ product | json }} not working in a .js file?

shenkwen
Shopify Partner
13 0 2

I have a `custom.js.liquid` file under my assets folder, and I have added this line to `theme.liquid`.

<script src="{{ 'custom.js' | asset_url }}" defer="defer"></script>

I am trying to output a product's title to javascript, in `custom.js.liquid`, I put

console.log({{ all_products['absolut-vodka'] | json }});

This line can't be recognized by the .js.liquid file. In frontend, in the `custom.js` file it becomes

console.log(null);

On the other hand, if I put

<script>console.log({{ all_products['absolut-vodka'] | json}});</script>

in the `theme.liquid` file, it can output the correct object.

What did I do wrong?

Replies 2 (2)

ui-gab
Shopify Partner
211 13 55

Sorry I have erased my first message as I had misread your question.

 

To correct my first answer:

https://community.shopify.com/c/Shopify-Design/Using-liquid-in-javascript-trying-to-get-collection-t...

 

The shopify staff there mentions it may not be possible to grab certain objects in the liquid js file.

 

ui-gab
https://www.uiavenue.ca
We specialize in data analytics. If I've helped you today, please give our give our app a try (15-day free trial) https://apps.shopify.com/ui-ave-analytics and maybe write a good review.
Send me a message if you want a free data analysis consultation.

summit_creative
Tourist
3 1 1

So I was having the same issue and came across this stack overflow https://stackoverflow.com/questions/25983518/whats-the-difference-between-js-and-js-liquid-in-shopif...

The js and css asset files are static and cannot load dynamic data. Instead you need to create a snippet with a script tag and have your custom.js in there. This worked for me then.