【问题标题】:EJS variable not define in htmlEJS 变量未在 html 中定义
【发布时间】:2020-12-21 04:06:31
【问题描述】:

我正在尝试从我的数据库中读取 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 未定义,但如果我将 &lt;% var newcompose; %&gt; 添加到 home 则它说 forEach 未定义。我也在用猫鼬。

【问题讨论】:

  • 你确定posts有值吗

标签: javascript node.js express mongoose ejs


【解决方案1】:

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

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

【讨论】:

  • @Maurice - 好的,如果我的回答有帮助,如果你能“接受”它,我将不胜感激。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 2019-09-30
  • 1970-01-01
相关资源
最近更新 更多