我正在尝试通过ejs从app.js获取数据,但它给出了错误。
computerSci学生
<%- include('header'); -%>
<h1><%= foo%></h1>
<p class = "home-content">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
<% for(var i = 0 ;i< posts.length;i++)%>
<%console.log(posts[i].title);%>// THIS LINE GIVES AN ERROR AND I AM UNANBLE TO POST THIS ON HOME.EJS
<%}%>
<%- include('footer'); -%>
我相信有人会帮助我删除此错误
答案 0 :(得分:0)
为了在模板中使用数据,您必须将数据传递到res.render()
。 res.render()
的格式如下:
res.render(view [, locals] [, callback])
第二个参数locals
是要传递给模板的数据。我无法从您的问题中确切说出您要执行的操作或要使用的模板,但是看来您可以执行以下操作:
app.post('/compose',function(req,res){
let posts = [{ title : req.body.title, post : req.body.post }];
res.render("compose", posts);
});
然后,将您的撰写模板更改为此:
<%- include('header'); -%>
<p class = "home-content">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
<ul>
<% posts.forEach(function(post) { %>
<li><%= post.title %></li>
<%})%>
</ul>
<%- include('footer'); -%>