Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use handlebars/mustache and bootstrap typeahead for rendering item

I would like to customize the item which is rendered by bootstrap-typeahead using handlebars template. Looking at the code it seems that the default item is <li><a href="#"></a></li>.

Let's suppose I would like to use an handlebars template for rendering my item.

I my opinion I should redefine the render function in this way (1).

My question is:
how should use the (1) with bootstrap-typeahead.js v2.1.0`?

Here is (2) the code about the options I am passing to $.fn.typeahead and (3) my handlebars/mustache template.


(1)

var renderItem = function (ul, user) {
    // user is the Backbone.Model
    return $('<li></li>')
        .data('item.autocomplete', user)
        .append(autocompleteItemTemplate(user.toJSON()))
        .appendTo(ul);
};

(2)

element.typeahead({
    minLength: 3,
    source: function () {
        var users = app.userCollection;

        users = _.map(users, function (user) {
            return user.get('first_name') + ' ' + user.get('last_name');
        });
        return users;
    }
});

(3)

<a>{{ first_name }} {{ last_name}}</a>
like image 799
Lorraine Bernard Avatar asked Aug 25 '12 08:08

Lorraine Bernard


1 Answers

You can overwrite the render method like this:

element.data( "typeahead" ).render = function ( items ) {
    var that = this;

    that.$menu.empty();
    items = $( items ).map(function (i, item) {
        i = renderItem( that.$menu, item ).attr( "data-value", item );
        i.find( "a" ).html( that.highlighter(item) );
        return i[0];
    });

    items.first().addClass( "active" );
    return this;
};

However, since Typeahead's source property must always be an array of strings or a function that returns an array of strings, in the renderItem function the user argument will be string, so I think you won't be able to use Handlebars.

like image 196
Bruno S. Avatar answered Oct 21 '22 07:10

Bruno S.