使用EJS模板传递变量

12

我正在为我的Express.js项目使用Ejs模板引擎,并且尽管将对象传递到视图blog.ejs文件中,但我在ejs文件中收到一个 blogpost未定义的错误。错误发生在我的<% blogpost.forEach(function(blogpost) { %>行。我认为这与我如何传递对象及其属性有关,但我按照指南操作并且它看起来是正确的。

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

博客.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>
1个回答

7

您没有将名为blogpost的数组变量传递到您的模板中,而是将这些变量传递给您的模板:

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

您可以使用render()代替当前的方法:
res.render('pages/blog', {
  blogpost: blogpost,
});

谢谢你的回答,它解决了我的错误信息,但是当我加载页面时,你的解决方案在h1标签中产生了一个“未定义”的结果。这可能是因为我在数据库中有多个条目,无法一次性提取所有条目吗?还是因为[blogpost]数组没有拉取数据? - cphill
我已经更新了解决方案。让我感到困惑的是,您将 POST 代码复制并粘贴到了您的 GET 路由处理程序中(类似于 blogpost.title = ... 这样的行)。 - mscdex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接