简体   繁体   English

车把:模板中有多个模型

[英]Handlebars: More than one model inside template

I am starting with Handlebars, and was wondering: 我从把手开始,想知道:

Is there the possibility to pass more than one model to the view? 是否可以将多个模型传递给视图?

I am passing my model with $(template(model)) to the view: 我将带有$(template(model))传递给视图:

    var source = $('#template').html();
    var template = Handlebars.compile(source);
    var model = this.model.toJSON();
    $(template(model)).appendTo(this.$parent);

So I can pass one variable with stored JSON data to the view. 因此,我可以将一个带有存储的JSON数据的变量传递给视图。 But what if I want to have two different variables/models in one template? 但是,如果我想在一个模板中有两个不同的变量/模型怎么办?

Is this possible? 这可能吗? This would be much easier than generating another template and loading into the other. 这比生成另一个模板并加载到另一个模板要容易得多。

A compiled Handlebars template just wants an object as its argument, you can build that object however you want. 编译的Handlebars模板仅需要一个对象作为其参数,您可以根据需要构建该对象。 If you want two models, just add an extra level of indirection: 如果需要两个模型,只需添加一个额外的间接级别:

var html  = template({
    model: this.model.toJSON(),
    other: this.other_model.toJSON()
});

and then inside your template you can say things like: 然后您可以在模板中说出类似以下内容:

{{model.attribute}}
{{other.other_attribute}}

and the like. 等等。


As an aside, a Backbone view adding HTML to anything other than this.$el (ie this.$parent ) is a bit dodgy. 顺便说一句,除了this.$el (即this.$parent )之外,将Backbone视图添加HTML到其他任何东西都有些狡猾。 Events are bound to this.$el so events won't work without help. 事件this.$el约束this.$el因此,事件将在没有帮助的情况下无法正常工作。 You'll probably an easier time if you turn that around a bit so that the parent places your view's $el somewhere so that your view can be self contained. 如果稍微改变一下位置,以便父级将视图的$el放在某个位置,以便视图可以独立存在,那么可能会更轻松。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM