Passing Liquid into Javascript
Combining Liquid Code and Javascript makes it possible to create powerful features in a Shopify Theme.
The tricky part is that Liquid is rendered on the server, and Javascript is interpreted in the browser
So how do you share data and objects from Liquid in your Javascript code?
It's actually pretty easy and requires only two steps
- Add a .liquid extension to the theme file containing the Javascript code
- Assign the Liquid data to a javascript variable, being sure to properly escape the code for the Javascript expression
The main "gotcha" is that certain Liquid objects are only available on specific pages. Read the documentation for a complete list
Some examples:
﹛% assign alert_msg =“message”%﹜
<form method=“post” onsubmit=“return
submitCheck(‘﹛﹛alert_msg﹜﹜’)”> …</form>
const product = ﹛﹛ product | json ﹜﹜
let title = product.title