How to pass variables to Pug's `script.` block?

眉间皱痕 提交于 2021-01-03 03:14:13

问题


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?


回答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 (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?



来源:https://stackoverflow.com/questions/49238052/how-to-pass-variables-to-pugs-script-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!