要在 EJS 中呈现的多个项目

Multiple items to render in EJS

我是我们编程的新手。我被渲染 JavaScript 变量卡住了。

能否请您给我一个解决的建议?

.ejs 中,我正在尝试遍历 table

      <tr>
        <% bodies.forEach(function(body){ %>
          <% try (typeof body.rowNum !== 'undefined') { %>
            <th scope="row"><%= body.rowNum %></th>
            <% if(typeof body.tick !== 'undefined') { %>
              <td><%= body.tick %></td>
            <% } %>
            <% if(typeof body.exDiv !== 'undefined') { %>
              <td><%= body.exDiv %></td>
            <% } %>
            <% if(typeof body.divYield !== 'undefined') { %>
              <th><%= body.divYield %></th>
            <% } %>
            <% if(typeof body.qty !== 'undefined') { %>
              <th><%= body.qty %></th>
            <% } %>
            <% if(typeof body.total !== 'undefined') { %>
              <th><%= body.total %></th>
            <% } %>
          <% } %>
        <% }) %>
      </tr>

下面是.js文件:

app.post("/", function(req, res){
   var bodies = {rowNum: 1, tick: tick, exDiv: exDiv, divYield: dividend, qty: 50, total: total}
   res.render("list", {bodies:bodies});
});

我收到的错误消息

SyntaxError: Unexpected token '(' in C:\Users\yoonl\Desktop\DividendTracker\views\list.ejs while compiling ejs

如果上述错误没有帮助,您可能想尝试 EJS-Lint: https://github.com/RyanZim/EJS-Lint 或者,如果您打算创建一个异步函数,请将 async: true 作为选项传递。 在新功能() 在 Template.compile(C:\Users\yoonl\Desktop\DividendTracker\node_modules\ejs\lib\ejs.js:661:12) 在 Object.compile(C:\Users\yoonl\Desktop\DividendTracker\node_modules\ejs\lib\ejs.js:396:16) 在 handleCache (C:\Users\yoonl\Desktop\DividendTracker\node_modules\ejs\lib\ejs.js:233:18) 在 tryHandleCache (C:\Users\yoonl\Desktop\DividendTracker\node_modules\ejs\lib\ejs.js:272:16) 在 View.exports.renderFile [作为引擎] (C:\Users\yoonl\Desktop\DividendTracker\node_modules\ejs\lib\ejs.js:489:10) 在 View.render(C:\Users\yoonl\Desktop\DividendTracker\node_modules\express\lib\view.js:135:8) 在 tryRender (C:\Users\yoonl\Desktop\DividendTracker\node_modules\express\lib\application.js:640:10) 在 Function.render(C:\Users\yoonl\Desktop\DividendTracker\node_modules\express\lib\application.js:592:3) 在 ServerResponse.render (C:\Users\yoonl\Desktop\DividendTracker\node_modules\express\lib\response.js:1012:7)

[问题]我不熟悉async如果下面的问题可以通过添加async函数来解决,能否请您分享一个如何使用它的例子?

谢谢,

您需要解决一些问题..

1.) 您期望模板中有一个 array,因为您使用 bodies.forEach(...) 但您传递了一个对象。通过执行以下操作解决此问题:

var bodies = [{rowNum: 1, tick: 123, exDiv: 123, divYield: 123, qty: 50, total: 123}];
res.render("list", {bodies}); // use Object Property Value Shorthand instead of {bodies:bodies}

2.) <% try (typeof body.rowNum !== 'undefined') { %> 这是不正确的语法,我想你想用 if 代替:

<% if (typeof body.rowNum !== 'undefined') { %>

在这种情况下,您的错误与 async 无关 - 它只是语法错误和传递给模板的数据不正确