简体   繁体   English

如何在Pug内联脚本中使用Pug局部变量?

[英]How to use pug local variables in pug inline scripts?

I have the following code (Chart.js piece): 我有以下代码(Chart.js段):

datasets: [{
                  label: 'Hashes/s',
                  data: numbersList,
                  backgroundColor: [
                      'rgba(255, 99, 132, 0.2)',
                      'rgba(54, 162, 235, 0.2)',
                      'rgba(255, 206, 86, 0.2)',
                      'rgba(75, 192, 192, 0.2)',
                      'rgba(153, 102, 255, 0.2)',
                      'rgba(255, 159, 64, 0.2)'
                  ],

Now I'm passing this local like so from the main app: 现在,我从主应用程序像这样传递了此本地信息:

require('../charter')((numbersList) => {
  res.render('index', {
    numbersList: numbersList
  })
})

Unfortunately it looks like it's only available to the top scope of the pug page. 不幸的是,它似乎仅可用于哈巴狗页面的顶部范围。 If I write h1=hashesList it will print out [1,2,3] (for example) but it seems the scope inside of pug scripts won't allow for this. 如果我写h1=hashesList ,它将打印出[1,2,3](例如),但看来pug脚本内部的作用域不允许这样做。

What am I missing? 我想念什么? Thanks. 谢谢。

In your pug template you need to use unescaped interpolation within your script as you stringify your data. 在帕格模板中,在对数据进行字符串化时,需要在脚本中使用未转义的插值

script.
  var numbersList = !{JSON.stringify(numbersList)};

This will output your variable as a browser-compatible JavaScript object. 这会将您的变量输出为与浏览器兼容的JavaScript对象。 Using the # symbol for escaped interpolation will not work here as it escapes quotes from " to \\\\" . 使用#符号进行转义插值在这里不起作用,因为它会将引号引号从"\\\\"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM