Can I change the templating engine in Typeahead.js?

Phil picture Phil · Feb 4, 2014 · Viewed 8.9k times · Source

Twitter Typeahead.js 0.10.0 now uses Bloodhound.js to interact with the server.

Is it possible to change the templating engine it uses from handlebars to underscore.js' or knockout.js punches' templating engine?

Answer

Phil picture Phil · Feb 4, 2014

Oh, I was blind to the obvious. In configuring twitter typeahead, in the templates option, in suggestion sub-option; there you can pick your view engine. To illustrate (taken from http://twitter.github.io/typeahead.js/examples/):

$('.example-twitter-oss .typeahead').typeahead(null, {
  name: 'twitter-oss',
  displayKey: 'name',
  source: repos.ttAdapter(),
  templates: {
    suggestion: Handlebars.compile([
      '<p class="repo-language">{{language}}</p>',
      '<p class="repo-name">{{name}}</p>',
      '<p class="repo-description">{{description}}</p>'
    ].join(''))
  }
});

The code above uses Handlebars. But you can use any templating engine that supports compile function. The compile function takes the user template and processes it as need be to get the HTML that needs to be rendered. If you want to use underscore, extend it to support a function called "compile" and reference that. The code illustrating this is below.

;(function (_) {
    'use strict';

    _.compile = function (templ) {
        var compiled = this.template(templ);
        compiled.render = function (ctx) {
            return this(ctx);
        }
        return compiled;
    }
})(window._);

I got this from Alan Greenblatt. The link is: http://blattchat.com/2013/06/04/twitter-bootstrap-typeahead-js-with-underscore-js-tutorial. His twitter typeahead examples are dated in that they were made for twitter typeahead version 0.9.3 which lacks bloodhound.js. However, it does provide a nice compile function for underscore templating engine.

Now, using underscore templating, the code will look like:

$('.example-twitter-oss .typeahead').typeahead(null, {
  name: 'twitter-oss',
  displayKey: 'name',
  source: repos.ttAdapter(),
  templates: {
    suggestion: _.compile([
      '<p class="repo-language"><%=language%></p>',
      '<p class="repo-name"><%=name%></p>',
      '<p class="repo-description"><%=description%></p>'
    ].join(''))
  }
});