我的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);
title
和source
都会将其设为pug文件。但不是events
:
Uncaught ReferenceError: events is not defined
如何正确传递script.
块内的变量?
答案 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)