Including External Template Files in a Backbone App Without a Server
I have a simple Backbone app that is being compiled down using gulp
and browserify
. I wanted to be able to include my template file with a simple node require()
method, but node doesn't like importing anything but JS files.
If I tried pulling in the template HTML with jQuery's $.get()
method, as is often recommended, I was getting a CORS error (in Chrome). My app can't have a server, so addressing this with headers was out.
It's also cumbersome to use inline templates like so many suggest. Eventually - finally - I figured it out: use stringify!
Install stringify
First I had to install the stringify module from npm:
npm install stringify --save-dev
Update Your gulpfile.js
Include stringify
I added the stringify module to the top of my gulpfile.js
file:
var stringify = require('stringify');
Update your browserify command
Next I had to tell browserify
to translate any required .html files as a string. Like so:
gulp.task('browserify', function() {
gulp.src(src_dir + '/js/main.js')
.pipe(
browserify({
transform: [
stringify(['.html'])
]
})
)
.pipe(concat('main.js'))
.pipe(gulp.dest(target_dir + '/js'));
});
Require your html files like normal
Now I could just include whatever template files I want, and they'll be considered a string. Here's one of my views
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
// This gets converted to a string now
var homeTemplate = require('../templates/home.html');
Backbone.$ = $;
var HomeView = Backbone.View.extend({
el: '#container',
template: _.template(homeTemplate),
render: function() {
var html = this.template({});
this.$el.html(html);
}
});
module.exports = HomeView;
Easy enough! I hope this saves you time.