I made a few changes to how I’m working with the templates and wanted to document that here.
Put it in the HTML
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> </script>
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