Handling “variable is not defined” with underscore template engine

by Cedric Dugas on November 29, 2011

One of the cool thing with backbone.js is that you can plug in about any javascript templating engine there is. Also another nice extra is that there is one already bundled with underscore.js that is quite powerful.

Personally the template engine provided with underscore cover most of my use cases and is enough for me, but there is one thing that I have found very unpleasant, you cannot pass undefined keys to it. Here an example:

var template =_.template($("#titlebar_tpl").html());
var data = {"title":"Planning"};
<script id="titlebar_tpl" type="text/template">
<input id="<%= id %>">
<span class="title"><%= title %></span>

There you go, in this example id will be undefined and will throw a js error, that is quite an hassle when you handle dynamic templates that might not always have all the data asked in the template.

Fortunately, there is an easy fix

While direct properties will throw an error, wrapping this in another object will do the trick. Here an example:

// Old way
var data = {"title":"Planning"};
// New way
var data = {"data": {"title":"Planning"}};
<script id="titlebar_tpl" type="text/template">
<input id="<%= data.id %>">
<span class="title"><%= data.title %></span>

Slightly painful code wise, but still a nice solution without headache. Another nice touch, you do not even have to check if the property exist, it will not show as undefined but just not show at all (You can of course check if it exists to add code logic in your template).

There you go!