Search code examples
node.jsexpresschart.jspug

How to pass a array from node to .js file (pugJs)


I am trying to render a chart (using ChartJS) as express response. The data points for the chart are stored in node as array. I have to pass it on to the chartJS function.

For that I'm currently using express's res.render() method. I have managed to pass the values to .pug file. Now i have to move the data points from .pug file to the .js file/ChartJS function.

How do i accomplish this? is this is the correct approach?

The end result I expect is that the array values stored in node has to be reflected on the .js file which has the ChartJS function.

I will be thankful for your help/advice of any kind.

Thanks!!


Solution

  • You need to use unescaped string interpolation and a stringify to turn your pug variable into a client-side browser variable:

    var arrayForChart = !{JSON.stringify(arrayInPug)};
    

    If the variable in express/pug is ['a', 'b', 'c'] then this will output:

    var arrayForChart = ['a', 'b', 'c'];
    

    Without the stringify you'll get something like this which will just throw an error in the browser as it's not valid JavaScript:

    var arrayForChart = [Object object];