简体   繁体   中英

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.

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

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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM