Templating improvements

Most of the visual elements in my gallery app are dynamically generated: menus, tags, item detail views and the grid of items. I’m using Underscore for this and it’s working out really well. I saw that their implementation was based on John Resig’s micro templates – which is a pretty interesting bit of JavaScript.

I made a few changes to how I’m working with the templates and wanted to document that here.

Put it in the HTML

Previously, my templates were in big strings in the JavaScript and were became very inconvenient to work around and update with structural changes. Placing the templates in the HTML makes a lot more sense and it’s easy to do. There are just a few things that you need to watch out for:

1. Place it in a <script> tag with an ID and a TYPE of ‘text/template’. As John describes on this micro template post, the type needs to be something the browser doesn’t understand and will ignore. Text/template is a logical choice.

Here’s my tag template

<script id="template__tag" type="text/template">
 <div class="tag"><%= tag %></div>

All of my template are in this file. I added an import into my main Jade file to integrate them into the final output.

2. The templates/scripts need to be in the <head> of your document. You cannot get to them with document.getElementByID() if not.

3. Trim whitespace from the beginning of the template source. If you indent the HTML under the script tag, whitespace will be present. When this is converted into a DOM element (at least by my method), it’ll be a Text node, not an Element node. A simple trim() will take care of this.

Simple templating helper module

I wrote a simple module to wrap retrieving the template HTML and the creation / processing of the Underscore template. This standardizes the way I work with the modules across my app and will make it easy to switch away from this system if I want to later.

I implemented caching on the first retrieval of the template HTML and creation of the template object. These can be expensive ops (especially creating the template object), so this saves a lot of time.

Example numbers …

The NTemplate.getTemplate function 1) gets the template HTML and 2) creates the Underscore template object. Iterating 10,000 times:

  • No cache: ~2218.643ms
  • Cache: ~0.3ms


Leave a Reply