I love Backbone.js. But it’s not perfect. One of my main problems with it is inline templates. Inline templates are templates that are contained within script tags within an HTML document. Almost every Backbone.js tutorial I’ve seen uses inline templates. But in the real world, this is a horrible way to build your web app.

Yet, it seems no one ever talks about this important piece of building real world web apps. There are some notable exceptions however. Angular.js lets you use external templates. Require.js has a plugin which lets you load templates as external dependencies, and many Backbone.js developers use and recommend this method. But, my opinion is that you shouldn’t be forced to use the entire Require.js library just for one feature.

That’s why I created a small script called TemplateManager. TemplateManager uses jQuery to asynchronously fetch and cache external template files. It also uses Underscore.js to pass the rendered template to a callback. And it uses Promises, actually jQuery’s Deferreds, to handle callbacks.

I like it because you can preload all your templates on initialization and because they are cached you can use them on demand later when you render your views. By preloading them, the requests happen in the background asynchronously so nothing is potentially blocked except whatever is rendered initially. You can also lazy load them and only fetch them when the view is created and rendered.

jQuery and Underscore are required for this, but Backbone is not. This allows you to use it with any application, although it works really well with Backbone since jQuery and Underscore are dependencies. I could have made it a Backbone plugin, but since it’s not a dependency, it can be used anywhere so I didn’t want to force that. I think in the future it would be useful to add support for other templating libraries so Underscore wouldn’t be a dependency in that case.

Check it out in the wizard-mvc project or on GitHub.


I also created a version of this for Marionette.js called Marionette.TemplateManager which is a Marionette plugin. I’ve been trying out Marionette recently, and I thought it would be nice to utilize this here too. One thing about Marionette is that it already has a TemplateCache object that caches inline templates internally. Marionette.TemplateManager takes advantage of this by using the TemplateCache instead of its own internal cache. It doesn’t return the compiled template with the promise however since Marionette also handles that internally. With Marionette, you can also change the default templating library so you don’t have to use Underscore templates.

Check it out in the wizard-mvc project or on GitHub.