How to use pug local variables in pug inline scripts?

3k Views Asked by At

I have the following code (Chart.js piece):

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.

What am I missing? Thanks.

1

There are 1 best solutions below

0
Graham On

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. Using the # symbol for escaped interpolation will not work here as it escapes quotes from " to \\".