EJS编译报错:Unexpected token ')' 问题排查求助
解决EJS编译时的SyntaxError: Unexpected token ')'问题
嘿,我一眼就揪出你代码里的问题啦!错误出在渲染订单产品列表的那段逻辑里,就是这部分:
<td><%= order.products.forEach(item => { %> <li> <%= item.title %>(<%= item.orderItem.quantity %>) </li> <% totalPrice += item.quantity * item.price; }); %> </td>
问题根源
- 错误使用输出标签包裹循环逻辑:
<%= %>是EJS用来把内容输出到页面的标签,但forEach方法本身没有返回值(执行完只会返回undefined),你把循环逻辑直接塞到<%= %>里,会让EJS解析器彻底懵掉,直接触发语法错误。执行循环逻辑应该用<% %>标签,它只负责运行代码不输出返回值。 - 变量引用不一致:你输出数量时用的是
item.orderItem.quantity,但计算总价时却写了item.quantity,这会导致总价计算出错,得保持引用一致才行。
修正后的核心代码片段
把产品列表的渲染部分改成这样:
<td> <ul> <% order.products.forEach(item => { %> <li><%= item.title %> (<%= item.orderItem.quantity %>)</li> <% totalPrice += item.orderItem.quantity * item.price; %> <% }); %> </ul> </td>
另外别忘了给<li>加上<ul>父标签,不然HTML结构不合法,浏览器渲染也会出问题哦。
完整修正后的EJS代码
<%- include('../includes/head.ejs') %> <%- include('../includes/navigation.ejs') %> <div class="container clearfix"> <h1>Your Orders</h1> <% if(orders.length <= 0) { %> <h2>You have no orders!</h2> <% } else {%> <table> <thead> <tr> <th>Order No</th> <th>Products</th> <th>Total</th> </tr> </thead> <tbody> <% orders.forEach(order => { let totalPrice = 0; %> <tr> <td><%= order.id %></td> <td> <ul> <% order.products.forEach(item => { %> <li><%= item.title %> (<%= item.orderItem.quantity %>)</li> <% totalPrice += item.orderItem.quantity * item.price; %> <% }); %> </ul> </td> <td><%= totalPrice %></td> </tr> <% }); %> </tbody> </table> <% } %> </div> <%- include('../includes/end.ejs') %>
这样修改后,EJS就能正常编译了,语法错误会消失,同时HTML结构更规范,总价计算也能正确执行啦。
内容的提问来源于stack exchange,提问作者Balduraan
相关产品推荐
相关产品推荐

