Skip to content Skip to sidebar Skip to footer

How To Pass Variables To Pug's `script.` Block?

I have this code in my index.pug file doctype html html head title= title body script(src=`${source}`) script. for (var event of events){ VClient.Even

Solution 1:

You need to basically render your variables in such a way that the end result gets interpolated as valid JS. It can be done with: !{JSON.stringify(events)}

for (varevent of !{JSON.stringify(events)}) ...

which should expand to:

for (varevent of ["AD_START","AD_COMPLETE"]) ...

Note the !{} which is for unescaped interpolation, as opposed to the more frequently used #{} which in this case wouldn't work as it would expand to something like ["..."] (i.e. escaped quotes)

CAUTION: Unescaped code can be dangerous. You must be sure to sanitize any user inputs to avoid cross-site scripting (XSS). See: How to pass variable from jade template file to a script file?

Post a Comment for "How To Pass Variables To Pug's `script.` Block?"