我正在尝试显示 JSON 数据,但出现此错误。有人可以帮我解决这个问题吗?
Error -- > Unexpected token ; in "/home/ubuntu/workspace/project_guest_book/views/pages/posts.ej
导致错误的代码如下:
<% var post = require(__dirname +"/userPosts.json")
var result= %>
<table>
<% for (var i=0; i<post.length; i++){
result += %>
<tr>
<th><% post[i].Name+ %></th>
<td><% post[i].Post %></td>
</tr>
<% } %>
<table>
最佳答案
EJS 预计不会按照您尝试使用的方式使用。
将 ejs 模板视为带有嵌入式 javascript 的标记,它编译为可以提供所需数据的函数,并返回最终的 html。
因此您不必担心将中间标记存储在变量中或 html 片段的串联中。
查看此 fiddle 中的实现:
<script id="template" type="text/html">
<table>
<% for (var i=0; i< posts.length; i++){ %>
<tr>
<th><%= posts[i].Name %></th>
<td><%= posts[i].Post %></td>
</tr>
<% } %>
<table>
</script>
-
// This can be loaded from an external file:
var posts = [{
Name: "Post1", Post: "Lorem ipsum dolor sit amet"
}, {
Name: "Post2", Post: "Lorem ipsum consecteuter adpiscing elit"
}]
var compiledTemplate = ejs.compile(document.getElementById('template').innerText)
console.log(compiledTemplate({ posts: posts }))
关于javascript - 如何将 JSON 数据获取到我的 ejs 模板中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326474/