从View中渲染数组而不需要在模板中进行循环

Backbone.js - Rendering array from View without making a loop in the template

本文关键字:循环 View 数组 不需要      更新时间:2023-09-26

我正在使用backbone加载页面的所有帖子。当点击"获取所有评论"链接时,加载帖子的评论。我从一个Ajax调用中得到所有的注释。

Social.Views.StreamsIndex = Backbone.View.extend({
    comment_template: JST['streams/comment'],
    comment_displayall: function(data, post_id) {
      this.$("#comments").html(this.comment_template({
        comment: data // Here data is array
      }));
    }
});

我有评论。jst。ejs文件其中现在有一个循环但我必须把它放在视图

  <% _.each(comment.comments,function(comment){ %> // I want to get rid of this Line
 <div class="stream_comment">
   <div class="stream_commentphoto">
    <a><img src="<%= comment.actor.thumbnail.url %>"></a>
   </div>
   <div class="stream_comm-content">
    <a href="#"><h5><%= comment.actor.displayName %></h5> </a>
    <p><%= comment.content %></p>
   </div>
 </div>
<%}%>

我怎么能摆脱循环内评论模板,通过添加循环在视图?

可能是这样的:

comment_displayall: function(data, post_id) {
    //clear any existing comments
    var $comments = this.$("#comments").empty();
    //render each comment separately and append to the view
    _.each(data.comments, function(comment) {
        $comments.append(this.comment_template({comment:comment});      
    }, this);
}

然后删除模板中的循环结构(第一行和最后一行)。

/代码样本未测试