最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass variables to Pug's `script.` block? - Stack Overflow

programmeradmin9浏览0评论

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 = `/${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?

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?

Share Improve this question asked Mar 12, 2018 at 14:45 Nick SlavskyNick Slavsky 1,3303 gold badges21 silver badges42 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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?

发布评论

评论列表(0)

  1. 暂无评论