Reputation: 10774
I'm trying to pass a value to a variable in javascript from express to a jade template.
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. 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
.
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
Upvotes: 0
Views: 1168
Reputation: 11052
I don't like the idea of templating my client javascript, and I had problems getting it to work when I tried it. So my go-to solution is to store the data in the dom with a data-*
attribute and access it from 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);
Upvotes: 0
Reputation: 14881
Try this:
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 20],
['CPU', !{JSON.stringify(CPU_value)}],
['Network', 68]
]);
Upvotes: 1