2013-04-23 44 views
0

我正在加载使用骨干网页的所有帖子。并在点击“获取所有评论”链接时加载评论。我收到来自Ajax调用的所有评论。Backbone.js - 从视图渲染数组,无需在模板中创建循环

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 
     })); 
    } 
}); 

comment.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> 
<%}%> 

我怎样才能摆脱循环的评论模板中,通过在视图中添加循环?

回答

1

也许是这样的:

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); 
} 

而简单地删除模板的循环结构(第一和最后一行)。

/代码示例没有测试

+0

谢谢..这工作.. .. – 2013-04-23 10:55:55