Possible to use a Liquid custom module tag inside javascript?

I have a script that drives a ‘Lightbox’ type image gallery as prt of my Detail page in a custom module. Is it possible to use custom module Liquid tags inside the javascript? eg.

{
“items”: [
{
“width”: ,
“caption”: “{{this[‘Caption1’]}}”,
“height”: 1250,
“fileName”: “{{this[‘Name’]}}”,
“origFileName”: “{{this[‘Name’]}}”,
“url”: “{{this[‘GalleryImage1’]}}”,
“_id”: “123123123”,
“type”: “image”,
“fileSize”: 545454
},
]
}

This doesn’t seem to work, so is there a way to inject the Liquid tag or is there any sort of workaround?

If your JS in on the page (not an external source) then yes, you can use Liquid to populate the JS. It’s just content at that point of rendering (front-end).
If you’re sample isn’t working it’s likely the Liquid output is not what you are expecting and something is breaking the JS, or in this case making the JSON invalid (like non-escaped HTML elements).

What does the rendered code look like?

1 Like

Actually, it looks like your JSON is not quite valid in your sample.
The “width” property has no value (needs an empty string perhaps “”) and that very last comma shouldn’t be included (unless there are more items…).

Thanks Adam - you’re right (as usual)… the generic ‘width’ was missing so broke the JS. Wasn’t 100% sure you could use Liquid in the JS but working OK now. Thanks again for your help (and patience) - that’s about a box of fine red I owe you - Cheers!

1 Like