在循环下划线JS模板 [英] loops in underscore js template

查看:148
本文介绍了在循环下划线JS模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

玉家伙,所以我有密钥对值这阵我用我的模型,其中:结果

Ok guys so I have this array of key pair values which I'm using as my model:

var acs = [{'label':'input box'},{'label':'text area'}];

在code的其余部分则如下:

the rest of the code goes as follows

var Action = Backbone.Model.extend({});
var action = new Action(acs);
var ActionView = Backbone.View.extend({
    tagName:"li",
    template: _.template($('#actions-template').html()),
    events:{
        "click":"makeInput"
    },
    render:function(){
        $(this.el).html(this.template(this.model.toJSON()));
        $(".hero-unit>ul").append(this.el);
        return this;
    },
    makeInput:function(){
        alert("im in");
    }
});
var actionView = new ActionView({model:action});
actionView.render();

问题是与问候的看法。我怎样才能通过循环,我通过,如果这模式是我想有结果的看法

The question is with regards to the view. How can I loop through the model I'm passing if this is the view I want to have

<script type="text/template" id="actions-template">
<% _.each(action, function(acs) { %> 
    <a class="btn"><%= label %></a>
<% }); %>
</script>

有什么毛病我的看法和循环,我相信。任何线索?
谢谢!

There is something wrong with my view and the loop I believe. Any clues? Thanks!

推荐答案

您一定希望做两件事情:

You'd probably want to do two things:


  1. 调整你提供给模板中的数据:

  1. Adjust the data you supply to the template:

$(this.el).html(this.template({
    action: this.model.toJSON()
}));


  • 调整模板的内部使用 acs.label 而不是标签

    <a class="btn"><%= acs.label %></a>
    


  • 演示: http://jsfiddle.net/ambiguous/xczBy/

    在第二个想法,我想你应该有一个集合,而不是单一的模式来工作。你想补充一点:

    On second thought, I think you should be working with a collection rather than a single model. You'd want to add this:

    var ActionCollection = Backbone.Collection.extend({
        model: Action
    });
    

    ,然后调整渲染使用 this.collection

        $(this.el).html(this.template({
            actions: this.collection.toJSON()
        }));
    

    然后启动事情是这样的:

    And then start things up like this:

    var actions = new ActionCollection(acs);
    var actionView = new ActionView({collection: actions});
    

    最后,请参照模板动作

    <% _.each(actions, function(acs) { %> 
    

    演示: http://jsfiddle.net/ambiguous/6VeXk/

    这将更好地满足骨干网的基于键/值模型。

    This would better match Backbone's key/value based models.

    这篇关于在循环下划线JS模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆