POSTS
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:
| /** | |
| * Allow underscore use of partials | |
| */ | |
| var underscorePartials = (function(){ | |
| var partialCache = {}; | |
| var mixin = { | |
| declarePartial: function(name, template) { | |
| partialCache[name] = _.template(template); | |
| }, | |
| partial: function(name, data) { | |
| return partialCache[name](data) | |
| } | |
| }; | |
| return mixin; | |
| })(); | |
| _.mixin(underscorePartials) |
Now you can declare a partial like this:
| _.declarePartial('tooltip', '<div class="toolTipWrapper"><div class="trigger"><i></i></div><div class="content"><%= tooltip.content %></div></div>'); |
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:
| <div class="field"> | |
| <% if(field.toolTip !== undefined) { %> | |
| <%= _.partial('tooltip', {tooltip: {content: field.toolTip}}) %> | |
| <% } %> | |
| </div> |
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!