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

前端 未结 1 925
耶瑟儿~
耶瑟儿~ 2020-12-17 23:53

I am trying to pass array of news to display on the screen but I somehow am getting empty array in the result in the browser

routes/rss.js



        
相关标签:
1条回答
  • 2020-12-18 00:28

    You can just pass it as an array, you don't need to stringify it when you are rendering. Then on your jade side you can just use for & each if you are only wanting to loop through.

    To get it to pass as an object to a script though you use an exclamation mark with single quotes then parse your object so you can use it. If you are going to pass it as an object to a script however and not use Jade's built-in iterating then you will need to stringify on your rss.js.

    routes/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)
      }); 
    

    views/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);
    
    0 讨论(0)
提交回复
热议问题