Partial templates with underscore.js

We’re doing some pretty advanced stuff at my company using underscore.js and to simplify some of it I wanted to use partial templates in my templates.

For example, we have different kind of tooltips all over our application. The structure is similar but the text and a few classes might change.

Underscore allows you to add your own functions using _.mixin(). And within an underscore template, all the underscore functions are still available.

So here’s the simple code:

Now you can declare a partial like this:

You declare your partials once, with a unique name. They are then globally available from within any other template.

And use it from within a template as follows:

That’s it, very easy and can save you some time by avoiding re-creating the same templates everywhere. Especially when you will need to change them!

Now …. time for the weekend!