用EJS模板传递variables

我为我的expressjs项目使用了Ejs模板引擎,尽pipe将我的对象传递给了我的视图blog.ejs文件,但我在我的ejs文件中收到了博文blogpost not defined错误。 错误发生在我的<% blogpost.forEach(function(blogpost) { %> line。我想这与如何传递对象及其属性有关,但我遵循指南,它看起来是正确的。

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> 

       

网上收集的解决方案 "用EJS模板传递variables"

您不会将名为blogpost的数组variables传递给您的模板,而是将这些variables传递给您的模板:

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

你可以做这个render()而不是你现在拥有的:

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