Using underscore.js templates with Twitter Typeahead

28 February 2013

I was adding Twitter’s new typeahead autocomplete to a project that was already using underscore.js templates. Instead of adding another template engine, I wrote this quick wrapper. (This is rendered Coffeescript.) Posting in case anyone else has the same problem.

Just set the template engine to _.templateTypeaheadCompatible.

_.templateTypeaheadCompatible = {
  compile: function(str) {
    return new _.templateTypeaheadCompiled(str);
_.templateTypeaheadCompiled = (function() {
  function templateTypeaheadCompiled(str) {
    this.compiledTemplate = _.template(str);

  templateTypeaheadCompiled.prototype.render = function(context) {
    return this.compiledTemplate(context);

  return templateTypeaheadCompiled;