How to best organize Underscore.js templates for use with Backbone.js?


Currently I have my main.jade file which is served using Express.js on Node.js. In the head of the jade file, I have all of my templates. As you can probably understand, this got unruly very quickly. I load the templates from Backbone.js using:


My app will have three versions: mobile, tablet, and desktop. I was wondering what the best way to organize my templates should be. I do not want to have ~30 templates listed in the head of my html file. How should I organize my templates? I would prefer to have 3 files somehow, one for each version. I do not want to serve a different URL from node.js/express.js depending on the version.

Problem courtesy of: Sam P


I actually ended up using the 'include' feature of jade.js to do what I needed. I have three .jade files for each version of my app and I include all of them in my main.jade. I am assuming I will ultimately result in using require.js for my project in the future, so thank you for your tips w/ that, eabait.

Solution courtesy of: Sam P


you can separate templates in files (such as phone-tpl.html) and put all of them in a /templates directory. Then you can load each of them through AJAX, in that case I recommend you to have a cache (in memory or localStorage) to minimize request numbers.

Another options is using RequireJS. Addy Osmani have proposed the use of text! plugin to load templates. A more sophisticated option was proposed by Alex Sexton, where you dont load templates as text but precompiled as Javascript functions (and when optimized with r.js all templates get bundled, so in production all templates are functions and you dont request them to the server).


Discussion courtesy of: eabait

You could put them into js files and load them with requirejs. That produces quite readable code and reduces dom dependence.

Discussion courtesy of: Johannes Degn

I ended up using Jade templates for everything - server and client side. No underscore templates. I used, which takes jade templates and precompiles them into a single js file. Advantages:

  1. No templates in your html files. Smaller, more sane markup
  2. Precompiled jade templates are blazing fast
  3. Jade files can still be used to render html
  4. Single template system

clientjade doesn't watch for file changes. So I made a cake task that would handle that. If you go that route, check out my cake task -

Discussion courtesy of: Steve Potter

This recipe can be found in it's original form on Stack Over Flow.