[英]passing a value from express to a javascript in jade
I'm trying to pass a value to a variable in javascript from express to a jade template. 我试图将值传递给javascript中的变量,从express传递到jade模板。
Here is my route in express: 这是我的快递路线:
app.get('/tmp', function(req, res){
res.render('tmp', {
title: 'Temperature',
CPU_value : 20,
});
});
then, Here is my jade template: 然后,这是我的翡翠模板:
html
head
h1= title
p= CPU_value
script(type='text/javascript', src='https://www.google.com/jsapi')
script(type='text/javascript')
- var myCPU_value = CPU_value
google.load('visualization', '1', {packages:['gauge']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 20],
['CPU', 20],
['Network', 68]
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
body
#chart_div
The variable of CPU_value
passed to p
works correctly, as same as the title. 传递给
p
的CPU_value
变量与标题一样正常工作。 It works. 有用。 But what I have not been able is to use the value of
CPU_value
in the array passed to the function google.visualization.arrayToDataTable
. 但是我还不能使用传递给函数
google.visualization.arrayToDataTable
的数组中CPU_value
的值。
I tried with: 我尝试过:
...
['CPU', CPU_value],
...
or 要么
....
var myCPU_value = CPU_value;
....
['CPU', myCPU_value],
....
none of them worked... 他们都没有工作...
how can I do this correctly? 如何正确执行此操作?
thanks 谢谢
Try this: 尝试这个:
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 20],
['CPU', !{JSON.stringify(CPU_value)}],
['Network', 68]
]);
I don't like the idea of templating my client javascript, and I had problems getting it to work when I tried it. 我不喜欢模板化客户端javascript的想法,并且在尝试时无法正常工作。 So my go-to solution is to store the data in the dom with a
data-*
attribute and access it from JS. 因此,我的首选解决方案是使用
data-*
属性将数据存储在dom中,然后从JS访问它。
//jade
html
head
h1= title
p#cpuValue(data-cpuvalue=locals.CPU_value)= locals.CPU_value
// client js
var myCPU_value =
document.getElementById('cpuValue')
.getAttribute('data-cpuvalue');
...
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 20],
['CPU', myCPU_value], // or +myCPU_value to coerce String>Number
['Network', 68]
]);
...
chart.draw(data, options);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.