Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I change the templating engine in Typeahead.js?

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?

like image 769
Phil Avatar asked Feb 04 '14 16:02

Phil


2 Answers

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(''))
  }
});
like image 57
Phil Avatar answered Oct 21 '22 19:10

Phil


The good news is that as stated by Steve Pavarno you don't need a template engine anymore. You can achieve the desired result by passing a function like so:

// ...
templates: {
    suggestion: function(data) { // data is an object as returned by suggestion engine
        return '<div class="tt-suggest-page">' + data.value + '</div>';
    };
}
like image 35
mdev Avatar answered Oct 21 '22 19:10

mdev