typeahead

typeahead template function

Posted on: March 16th, 2014 by taff 2 Comments

Sometimes when using typeahead you need to retrieve different data which for example links to a particular page as opposed to carrying out a search. The typeahead template function is just the job for this, but let's have a look at the data first. In the following example I will be retrieving two types of data. If you need help with this, look into retrieving multiple sources with typeahead. The first data retrieved is the search suggest which I won't go into deeper as this example concentrates on using the typeahead template function.

The JSON data I retrieved by the call to products.php has the following structure (this would be the data retrieved when typing netbook into the searchbar:

[
{"product_id":"1","value":"Aspire Netbook"},
{"product_id":"2","value":"ASUS Netbook"},
{"product_id":"3","value":"Lenova Netbook"}
]

Nothing to difficult here. The idea is that the data retrieved can be used to generate a direct link to the product, saving the need for a user search. Using a general MVC standard, the url would be product/details/product_id where product is the controller, details the action within said controller and product_id would be the parameter passed to our action If I want to visit the ASUS Netbook page, I would go to product/details/2. Let's see how the typeahead template function can help us to achieve this.

jQuery(document).ready(function () {
jQuery('#Search').typeahead([
{
limit: 5,
name: 'searchterms',
remote: '/searchterms.php?q=%QUERY',
header: '
<h3 class="suggest-elements">Search Terms</h3>
'
},
{
limit: 3,
name: 'products',
remote: /products.php?q=%QUERY,
header: '
<h3 class="suggest-elements">Products</h3>
',
template: function (data) {
return '
<p class="searchSuggest-product"><a href="/product/details/' + data.product_id + '">' + data.value + '</a></p>
';
}
}
]);
});

As you can see, the typeahead template function is a simple callback function that is passed a data array and returns some HTML. Although typeahead offers the ability to use Handlebars or Hogan to compile the template, as you can see on the typeahead examples page, I find this version better as it saves me using an additional javascript libarary. I hope this short example helps you get to grips with the typeahead template function. Feel free to comment if anything is unclear or you need further assistance

2 Responses

  1. Csaba Toth

    December 1, 2015

    I try to use function as a template, but it doesn’t work so far for me. I don’t want to install even Hogan for this.

    Reply
  2. Csaba Toth

    December 1, 2015

    All right, so it’s not simply “template: function (data) { …”, but instead “templates: suggestion: function (data) { …”

    Reply

Leave a Reply