Reputation: 4319
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:
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. 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.
Upvotes: 2
Views: 1320
Reputation: 434785
A compiled Handlebars template just wants an object as its argument, you can build that object however you want. 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
(i.e. this.$parent
) is a bit dodgy. Events are bound to this.$el
so events won't work without help. 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.
Upvotes: 4