0
votes

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?

1
Not sure this is possible community.shopify.com/c/Shopify-Design/… look at answer from Caroline_SchnapMoshe Sommers

1 Answers

2
votes

Asset files are resources that Shopify strongly caches. This means that you cannot access any Liquid variables that might be change from page to page, customer to customer, etc. Product details can be updated at any arbitrary time by yourself or an app, so this also falls under the category of things that are not available in your asset files.

Inside your .js.liquid file, the main things you have access to are:

  • Translation settings
  • Theme settings

... and that's about it. It may be worth noting that theme and language settings are both located with your theme files, and this may have something to do with Shopify's decisions around these Liquid restrictions

If you want to get the product details for your absolut-vodka product, you can use Shopify's storefront API to get the details you need. (eg: by fetching /products/some-product-handle.js). For example:

function getProductThenDoStuff(productHandle, callbackFunction){
  fetch('/products/' + productHandle + '.js')
    .then(function(response){ return response.json() })
    .then(callbackFunction)
}