I'm trying to setup custom template with Typeahead.js
My code is:
var countries = new Bloodhound({
datumTokenizer: function(d) {
return Bloodhound.tokenizers.whitespace(d.value);
},queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 100,
remote: {
url: 'http://www.domain.com/json.php?action=countries&q=%QUERY'
}
});
countries.initialize();
$('.lang').typeahead(null, {
name: 'countries',
source: countries.ttAdapter(),
template: [
'<p class="lang-id">{{lang_id}}</p>',
'<p class="value">{{value}}</p>'
].join(''),
engine: Hogan
});
It works fine, but the template setting is ignored - I still get default dropdown. What am I doing wrong?
EDIT: I also tried:
$('input').typeahead(null, {
name: 'countries',
displayKey: 'value',
source: countries.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'no results found',
'</div>'
].join('\n'),
suggestion: '<p><strong>{{value}}</strong> – {{id}}</p>'
},
engine: Hogan
});
which throws an error:
Property 'suggestion' of object #<Object> is not a function
Looking at the documentation, you can see that the name is templates and not template - like in you show in your second example. The issue you have there is that suggestion needs to be a function, not a string. In the bottom example of custom templates you can see they use Handlebars.compile which returns a function which takes a single parameter containing the data to render a template with - and returns a string that is the generated HTML. If you do not want to use Handlebars you could do something like (please note that for simplicity I do not escape the data in my example. For a proper solution you should escape data.value and data.id to make sure you do not introduce XSS vulnerabilities):
$('input').typeahead(null, {
name: 'countries',
displayKey: 'value',
source: countries.ttAdapter(),
templates: {
empty: [
'<div class="empty-message">',
'no results found',
'</div>'
].join('\n'),
suggestion: function(data){
return '<p><strong>' + data.value + '</strong> - ' + data.id + '</p>';
}
},
engine: Hogan
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With