簡體   English   中英

在node.js中將數組傳遞給jade模板時遇到問題

[英]Having problems with passing array to jade template in node.js

我試圖傳遞一系列新聞在屏幕上顯示但我在某種程度上在瀏覽器的結果中得到空數組

路線/ rss.js

...
var news = [];
...
          var this_news = { 
            'title': item.title,
            'description': item.description
          }   
          news.push(this_news);
...
  res.render('rss', { 
    title: 'Node.js based RSS reader',
    newsi: JSON.stringify(news)
  }); 

意見/ rss.jade

extends layout

block content
  h1= title
  p Welcome to #{title}
  p Sure why not 
  script(type='text/javascript').
    var inews = !{newsi};

編輯

好的,我得出結論,問題在於我的'非回調邏輯'

這是我的代碼:

var FeedParser = require(__dirname + '/../node_modules/feedparser')
  , request = require(__dirname + '/../node_modules/request');

exports.news = function(req, res){

  var news = []; 
    request('http://feeds.feedburner.com/niebezpiecznik/')
    .pipe(new FeedParser())
      .on('error', function(error) {
        //...
      })  
      .on('meta', function (meta) {
        console.log('===== %s =====', meta.title);
        console.log('**** %s ****', meta.description);
        console.log();
      })  
      .on('readable', function() {
        var stream = this, item;
        while (item = stream.read()) {

          var this_news = { 
            'title': item.title,
            'description': item.description
          }   
          news.push(this_news);

        }   
        res.render('rss', { 
          title: 'Node.js based RSS reader',
          newsi: JSON.stringify(news)
        }); 
    }); 

};

它幾乎可以工作,但它讓我得到了未處理的異常。 我該怎么處理?

您可以將其作為數組傳遞,在渲染時不需要對其進行字符串化。 然后在你的玉器一側如果你只是想要循環,你可以使用for和each

要將它作為對象傳遞給script盡管您使用帶單引號的感嘆號,然后解析對象以便可以使用它。 如果你要將它作為對象傳遞給腳本但是不使用Jade的內置迭代,那么你需要在你的rss.js上進行字符串化。

路線/ rss.js

...
var news = [];
...
          var this_news = { 
            'title': item.title,
            'description': item.description
          }   
          news.push(this_news);
...
  res.render('rss', { 
    title: 'Node.js based RSS reader',
    newsi: JSON.stringify(news)
  }); 

意見/ rss.jade

extends layout

block content
  h1= title
  p Welcome to #{title}
  p Sure why not
  script(type='text/javascript').
    // Pass as regular array here
    var inews = JSON.parse('!{newsi}');
    console.log(inews);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM