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

China☆狼群 提交于 2019-12-20 04:15:43

问题


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!!


回答1:


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


来源:https://stackoverflow.com/questions/55528213/how-to-pass-a-array-from-node-to-js-file-pugjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!