Adding an “include” tag to Underscore.js templates

I use Backbone.js a lot lately, and since Backbone requires Underscore.js, I usually end up using Underscore’s templates rather than introducing another Javascript library dependency like Mustache templates. But Underscore’s micro-templating language has an omission that bothered me today: templates can’t include each other.

So here’s a quick and dirty <% include %> tag for Underscore templates:

As you can see, the code simply replaces tags like

with the contents of the element with id “foo”. Use it by throwing code like this into the body of your HTML page:

And in your Javascript code, do this:

Enjoy! I leave as an exercise for the reader:

  1. Cache included templates so the template() function needn’t keep doing document.getElementById().innerHTML for an often-included template
  2. Create replaceable blocks in templates
  3. Pass variables from one template to another
  • Dav_twix
    Great, It's a cleaner solution than write html tag with print() thanks to share it
  • http://twitter.com/unicodefreak unicodefreak
    Thank you for the solution. I modified it to use jQuery and get rid of special template() function. https://gist.github.com/1901458
    • http://emptysquare.net/ A. Jesse Jiryu Davis
      Neat!