How to bind dynamic element attributes using handlebars in twitter typeahead

528 Views Asked by At

I'm working on an autocomplete snippet using twitter typeahead which needs template modification. the thing is I want to dynamically bind class names to templates using handlebarjs template engine. my code so far :

var terms = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace("title"),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        limit: 10,
        remote: {
            // url points to a json file that contains an array of country names, see
            // https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
            url: '/results?q=%QUERY&r=all',
            // the json file contains an array of strings, but the Bloodhound
            // suggestion engine expects JavaScript objects so this converts all of
            // those strings
            filter: function (data) {
                return $.map(data, function (val, i) {
                    return {
                        title : val._source.title,
                        address : val._source.address,
                        type : val._type
                    };
                });
            },
            ajax :{
                type:"GET"
            }
        }
    });

    // kicks off the loading/processing of `local` and `prefetch`
terms.initialize();
$("#search-input").typeahead({
        highlight: true,
        hint:false
    }, {
        name: 'terms',
        displayKey: 'title',
        // `ttAdapter` wraps the suggestion engine in an adapter that
        // is compatible with the typeahead jQuery plugin
        source: terms.ttAdapter(),
        templates:{
            header:Handlebars.compile([
                '<div class="list-group">'
            ].join('')),
            suggestion:Handlebars.compile([
                    '<a href="#" class="list-group-item">',
                        '<div class="type-{{type}} pull-right"></div>',//here it doesn't echo type-article,type-doctor,...
                        '<h4 class="list-group-item-heading">{{title}}</h4>',
                        '<p class="list-group-item-text">{{address}}</p>',
                    '</a>'
            ].join('')),
            footer:Handlebars.compile([
                '</div>'
            ].join(''))
        }

    });

I have problem at comment section. Thanks for your help.

0

There are 0 best solutions below