下划线模板通过_.each显示对象数组

Underscore template display array of objects via _.each

本文关键字:each 显示 对象 数组 下划线      更新时间:2023-09-26

我在用_.template为每个注释循环打印一个简单的代码时遇到了问题。

<% _.each([comments], function(i) { %>  <p><%= i %></p> <% }); %>

打印[object object]

<% _.each([comments], function(i) { %>  <p><%= JSON.stringify(i) %></p> <% }); %>

打印:

[{"comment":"Mauris quis leo at diam molestie sagittis.","id":263,"observation_id":25}]

我已经试过了:

<% _.each([comments], function(i) { %>  <p><%= i.comment %></p> <% }); %>
空白

<% _.each([comments], function(i) { %>  <p><%= i.get('comment') %></p> <% }); %>

Uncaught TypeError: Object [Object Array]没有get方法

<% _.each([comments], function(i) { %>  <p><%= comment %></p> <% }); %>
空白

假设comments是模型中的数组:

<% _.each(comments, function(comment) { %>  
  <p><%= comment.comment %></p> 
<% }); %>