首页 > 解决方案 > EJS 变量未在 html 中定义

问题描述

我正在尝试从我的数据库中读取 JSON 文件。这是渲染的页面。

    <% newcompose.forEach(function(post){ %>

        <h1><%= post.caption %></h1>
        <p><%= post.text %></p>

    <% }); %>

这就是我将值传递给newcompose.

Post.find({}, function(err, posts){
    if(!err){
        res.render("home", {newcompose: posts});
    }
});

它说 newcompose 未定义,但如果我添加<% var newcompose; %>到 home 然后它说 forEach 未定义。我也在使用猫鼬。

标签: javascriptnode.jsexpressmongooseejs

解决方案


我使用以下代码测试了您的模板:

const ejs = require('ejs');

let template = `
<%newcompose.forEach(function(post){%>
    <h1><%=post.caption%></h1>
    <p><%=post.text%></p>
<%});%>
`;

const renderData = {
    newcompose: [
        {
            caption: "test caption",
            text: "test text",
        }
    ]
};
const output = ejs.render(template, renderData);

console.log(output);

输出是:

    <h1>test caption</h1>
    <p>test text</p>

所以你的模板很好。这意味着问题出在您的find函数上,或者您如何处理回调参数。

如果您使用的是 mongo,这可能是因为 find 返回了一个游标,因此您需要像这样显式调用 toArray 函数:

collection.find().toArray(function(err, documents) {

按照:https ://mongodb.github.io/node-mongodb-native/api-generated/cursor.html


推荐阅读