如何将变量传递给Pug的`script.`块? [英] How to pass variables to Pug's `script.` block?

查看:69
本文介绍了如何将变量传递给Pug的`script.`块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 index.pug 文件中有此代码

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

这是我将Express中的变量传递给pug的方式.

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

title source 都放入pug文件.但不是事件:

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

Uncaught ReferenceError: events is not defined

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

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

推荐答案

您基本上需要以最终结果作为有效JS插值的方式呈现变量.可以使用以下方法完成:!{JSON.stringify(events)}

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)}) ...

应扩展为:

for (var event of ["AD_START","AD_COMPLETE"]) ...

请注意用于!{} 未转义的插值,与更常用的#{} 相对,后者在这种情况下不起作用,因为它会扩展为类似 [& quot; ...& quot;] (即转义的引号)

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)

注意:未加密的代码可能很危险.您必须确保清除所有用户输入的内容,以避免跨站点脚本(XSS).请参阅:如何将变量从玉模板文件传递到脚本文件?

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?

这篇关于如何将变量传递给Pug的`script.`块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆