如何将变量传递给Pug的`script.block?

时间:2018-03-12 14:45:17

标签: javascript node.js express pug

我的index.pug文件

中有此代码
doctype html
html
  head
    title= title
  body
    script(src=`${source}`)
    script.
      for (var event of events){
        VClient.Event.subscribe(event, createDiv);
      } 

以下是我如何将变量从Express传递给帕格。

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);

titlesource都会将其设为pug文件。但不是events

Uncaught ReferenceError: events is not defined

如何正确传递script.块内的变量?

1 个答案:

答案 0 :(得分:3)

您需要基本上渲染变量,使最终结果作为有效JS进行插值。可以使用:!{JSON.stringify(events)}

完成
doctype html
html
  head
    title= title
  body
    script(src=`${source}`)
    script.
      for (var event of !{JSON.stringify(events)}) {
        VClient.Event.subscribe(event, createDiv);
      }

应扩展为:

for (var event of ["AD_START","AD_COMPLETE"]) {
  VClient.Event.subscribe(event, createDiv);
}

请注意!{}用于unescaped interpolation,而不是频繁使用的#{},在这种情况下不会有效,因为它会扩展为{{1} }(即转义引号)

PS:您也可以["..."]代替script(src=source)