Reputation: 4089
I'm making a backboneJS / HandlebarsJS single page project and I'm a bit of a noob with backbone (I normally use AngularJS). I want to keep each template (header, sidebar, footer, content's) in separate files for organization.
I've read a few post that say you should keep the templates in separate files for development and then combine them into one file for production. I'm pretty sure that they would be .html files and I'm not sure what tool to combine them with.
What is the correct way to do load templates from files? And do I combine the files into one and import it? Is there a tool to do this easier?
If you have a tutorial that explains the appropriate structure that would be great.
Please and Thank you!
Upvotes: 1
Views: 288
Reputation: 3136
I would recommend using RequireJS for dependency management.
With RequireJS you will define a view like
define(['text!path/to/template/view.html'], function (templateContent) {
var View = Backbone.View.extend({
template: _.template(templateContent),
render: function () {
this.$el(this.template())
}
});
return view;
});
Also r.js can be used for concatenating the template files(JS files also) into single file for performance reasons during build.
Upvotes: 1
Reputation: 76209
Handlebars templates are usually shipped in compiled (=JavaScript) form, which increases performance quite a bit. To do this properly, it makes a lot of sense to use a build tool like Grunt and the grunt-contrib-handlebars task. It generates a single JavaScript file out of all templates and, by default, stores the templates in the global JST
object, so you could use it like this:
Backbone.View.extend({
template: JST['mytemplate.hbs'],
render: function () {
this.$el.html(this.template());
}
});
Of course this is just one way out of many; I personally prefer Browserify with the hbsfy transform, which allows me to write code like this:
Backbone.View.extend({
template: require('../templates/mytemplate.hbs'),
render: function () {
this.$el.html(this.template());
}
});
Upvotes: 1