从快递到jade客户端javascript传递数组

时间:2013-10-02 03:21:20

标签: javascript node.js express pug

我有这个玉模板:

html
  head
    script(type="text/javascript" src="https://www.google.com/jsapi")
    script(type='text/javascript')
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
      var data = google.visualization.arrayToDataTable([
      ['Date', 'Tin_A' ],

       - each datapoint in myData
            "[" + datapoint.date + "," + datapoint.value + "],"

      ]);
      var options = {
      title: 'bla'
      };
      var chart = new google.visualization.LineChart(document.getElementById('chart_line'));
      chart.draw(data, options);
      }


  body
    h1= title
    #chart_line

我正在使用此调用在express / node.js中呈现jade模板:

app.get('/', function(req, res){
  sensors.findSensorAllData(2, 2, function (error,emps){
        console.log(emps);
        res.render('tmp', {
            title : 'Temperatures in a row',
            myData : emps
        });
    });
});

console.log(emps)的输出是:

[ { _id: 524b8642028e167fb0e3661d,
    sensor_id: 2,
    value: 49,
    date: Tue Oct 01 2013 20:34:40 GMT-0600 (CST) },
  { _id: 524b863d028e167fb0e3661c,
    sensor_id: 2,
    value: 19,
    date: Tue Oct 01 2013 20:34:35 GMT-0600 (CST) } ]

渲染出现后,我希望jadecrip中的值在jade模板中...但它不起作用。我在纯文本中只得到相同的行,好像行- each datapoing in myData没有意义......我做错了什么?感谢

---编辑: 如果我替换行

,一切正常
- each datapoint in myData
            "[" + datapoint.date + "," + datapoint.value + "],"

  ['2004',  20],
  ['2005',  30],
  ['2006',  40]

3 个答案:

答案 0 :(得分:1)

我认为由于括号周围的引号,您可能会意外地注入String而不是Array:

- each datapoint in myData
        "[" + datapoint.date + "," + datapoint.value + "],"

我对Jade不太熟悉,但我想你可能想要做以下事情:

- each datapoint in myData
        [#{datapoint.date}, #{datapoint.value}],

此外,在您提供的示例数据中,您只使用Date的year部分,但datapoint.date属性的内容可能是完整的Date对象,我不确定是否是你想要的用途。

答案 1 :(得分:1)

请参阅此问题的所选答案,了解您尝试做的事情为何无效。 (JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

基本上,只要您点击脚本标记,就会告诉Jade解析器以原始形式处理事物,并且不会进行进一步处理。你真正想要做的是重做代码的脚本标记,如下所示:

- if (typeof(pins) != "object")
!= "<script type='text/javascript'>"
!=   "google.load('visualization', '1', {packages:['corechart']});
!=   "google.setOnLoadCallback(drawChart);
!=   "function drawChart() {
!=   "var data = google.visualization.arrayToDataTable([
!=   "['Date', 'Tin_A' ],"
- forEach datapoint in myData
  !=   "[" + datapoint.date + "," + datapoint.value + "],"

!=   "]);"
!=   "var options = {"
!=   "title: 'bla'"
!=   "};"
!=   "var chart = new google.visualization.LineChart(document.getElementById('chart_line'));"
!=   "chart.draw(data, options);"
!=   "}"

试试这个,但我相当肯定它应该有用。

PS:上面的链接(我相信)清楚地说明为什么上一个答案应该是不正确的,因为你不能在Jade脚本标签内部进行那种模板占位符插值。

答案 2 :(得分:1)

丑陋警报:

script
  ...
  var data = google.visualization.arrayToDataTable(['Date', 'Tin_A' ].concat(!{JSON.stringify(myData.map(function(i) { return [ i.date, i.value ] })) }));