Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.Event.subscribe(event, createDiv);
      } 

And here is how I pass the variables from Express to pug.

var express = require('express');
var app = express();
app.set('view engine', 'pug')

app.get('/', function(req, res){
    var id = req.query.id || 23717;
    var source = `https://some.source.url/${id}.js`;
    res.render('index',
    {title: 'Preview Embed', source: source, events:["AD_START","AD_COMPLETE"]});
});
app.listen(5000);

Both title and source make it to the pug file. But not the events:

Uncaught ReferenceError: events is not defined

How do I correctly pass the variable inside the script. block?

like image 417
Nick Slavsky Avatar asked Jan 28 '23 12:01

Nick Slavsky


1 Answers

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 (var event of !{JSON.stringify(events)}) ...

which should expand to:

for (var event 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?

like image 193
laggingreflex Avatar answered Jan 31 '23 05:01

laggingreflex