2014-08-31 128 views
4

我爲我的expressjs項目使用Ejs模板引擎,儘管將我的對象傳遞給我的視圖blog.ejs文件,但我在我的ejs文件中收到blogpost not defined錯誤。我的<% blogpost.forEach(function(blogpost) { %>行發生錯誤。我認爲這與傳遞對象及其屬性有什麼關係,但我遵循指導原則,看起來是正確的。傳遞變量與EJS模板

routes.js:

//blog 
    router.route('/blog') 

     // START POST method 
     .post(function(req, res) { 

      var blogpost = new Blogpost(); // create a new instance of a Blogpost model 

      blogpost.title = req.body.title; // set the blog title 
      blogpost.author = req.body.author; // set the author name 
      blogpost.content = req.body.content; // set the blog content 
      blogpost.date = req.body.date; // set the date of the post 
       //Save Blog Post 
       blogpost.save(function(err) { 
        if (err) 
         res.send(err); 

        res.json({ message: 'Blog created.' }); 
       }); 

     }) // END POST method 


     // START GET method 
     .get(function(req, res) { 
      Blogpost.find(function(err, blogpost) { 
       if (err) 
        res.send(err); 

       blogpost.title = req.body.title; // update the blog title 
       blogpost.author = req.body.author; // set the author name 
       blogpost.content = req.body.content; // update the blog content 
       blogpost.date = req.body.date; // set the date of the post 

       res.render('pages/blog', { 
        title: blogpost.title, 
        author: blogpost.author, 
        content: blogpost.content, 
        date: blogpost.date 
       }); 
      }); 
     }); // END GET method 

blog.ejs:

<html> 
<head> 
    <% include ../partials/head %> 
</head> 

<body> 

    <header> 
     <% include ../partials/header %> 
    </header> 

    <div class="grid"> 
     <div class="col-1-1"> 
      <div class="body-content"> 
       <% blogpost.forEach(function(blogpost) { %> 
        <h1><%= blogpost.title %></h1> 
        <% }); %> 
      </div> 
     </div> 

    </div> 




    <footer> 
     <% include ../partials/footer %> 
    </footer> 

</body> 
</html> 

回答

3

你不及格叫blogpost到您的模板,你是不是通過這些變量對模板的數組變量:

title: blogpost.title, 
author: blogpost.author, 
content: blogpost.content, 
date: blogpost.date 

你可以做到這一點render()而不是你目前有一個:

res.render('pages/blog', { 
    blogpost: blogpost, 
}); 
+0

謝謝你的答案,它解決了我的錯誤信息,但你的解決方案在我加載頁面時在h1標記中呈現'undefined'結果。這可能是因爲我的數據庫中有多個條目,並且它不能一次拉出所有條目?或者更多是因爲'[blogpost]'數組沒有提取數據? – cphill 2014-09-01 01:18:50

+0

我更新瞭解決方案。我猜是什麼讓我失望了,是因爲你已經將'POST'代碼複製並粘貼到'GET'路由處理程序('blogpost.title = ...'種類的行)。 – mscdex 2014-09-01 01:31:42