javascript - 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 未定义。我也在使用猫鼬。
解决方案
我使用以下代码测试了您的模板:
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
推荐阅读
- cron - 每月第一个星期二的 NCRONTAB 用于 Azure 函数
- c++ - 在 Windows 上使用 C++ 运行 bash 脚本
- reactjs - 在 react+D3 中将更新逻辑与 useEffect 解耦
- html - 如何在图像文件中插入视频链接
- javascript - 如何使用 Javascript 从我的浏览器重定向到相机本机应用程序?
- react-native - React Native 钩子 - 正确使用 useEffect()?
- javascript - 如何使用带有 Javascript 的面向对象编程来操作 HTML DOM 元素
- halcon - 来自 HALCON 中的 3D 点的 2D
- python - Python - 正则表达式(Re.Escape,Re.Findall);如何:查找子字符串 + 字符串中子字符串之外的多个字符?
- ruby-on-rails - Rails Postgres - Jsonb 列查询