Custom template with jQuery Typehead using Ajax

105 Views Asked by At

This is what I have tried so far and it works fine without a custom template. However I need to show some more data, such as images etc., within the search result. How can I call a custom template along with AJAX?

<input type="text" class="site-search" name="search">
var path = "{{ route('site-search') }}";

$('input.site-search').typeahead({
  hint: true,
  highlight: true,
  display: 'value',
  source: function (query, process) {
    return $.get(path, { query: query }, function (data) {
      return process(data);
    });
  }
});
1

There are 1 best solutions below

0
On

See the docs. Just make your template function and use |raw modifier to show clean, non-escaped html.

display: "series",
template: function (query, item) {
    var template = '<span data-series="{{series|raw}}">' +
        '{{series}}, {{seasons}} seasons -' +
        '<var data-rating="{{rating|raw}}">{{rating}}/10</var></span>'

    if (item.rating >= 9) {
        template += '<span class="ribbon">Top Rated</span>';
    }
    return template;
},
source: {
    data: [
        {
            series: "Breaking Bad",
            seasons: 5,
            rating: 9.6
        }
        ...
    ]
}