Using jQuery.html() with underscore.js template

Just a quick gotcha that cost me some time and frustration trying to resolve…

In my DOM, I have an element #item-template that contains a simple mustache-style template string: <span class="item-name"></span>. I’m using underscore.js’s _.template to interpolate model information from backbone.js (as a side note, I’ve just recently started playing around with backbone, and I think I’ve fallen in love. But, more on that later).

Anyway, the interpolation wasn’t working. When a model would render, it would render the template string itself, escaped for html entities, instead of the properly-interpolated string. Turns out, the problem was in how I was using jQuery to fetch #item-template‘s content for processing. What I was doing:

As it turns out, the output of jQuery.html(), when used to get the innerHTML of a DOM element, is escaped, so my template string as it was being passed looked like &lt;span class="item-name"%gt;... The simple solution was to just use jQuery.text() instead:

And that worked like a charm. Hope that helps someone else with a similar problem.