Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead custom template Without Handlebars

I'm trying to implement the Typeahead.JS "Custom Template" example.

$('#custom-templates .typeahead').typeahead(null, {
  name: 'best-pictures',
  displayKey: 'value',
  source: bestPictures.ttAdapter(),
  templates: {
    empty: [
      '<div class="empty-message">',
      'unable to find any Best Picture winners that match the current query',
      '</div>'
    ].join('\n'),
    suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')
  }
});

Specifically this line:

suggestion: Handlebars.compile('<p><strong>{{value}}</strong> – {{year}}</p>')

Initially I didn't realise you need to explicitly require Handlebars as a dependancy:

Uncaught ReferenceError: Handlebars is not defined

When I remove Handlebars...

suggestion: '<p><strong>' + value + '</strong> – ' + year + '</p>'

It gives another JS error:

Uncaught ReferenceError: value is not defined

Is it possible to use a custom view template without using Handlebars engine?

like image 995
Daniel Morris Avatar asked Mar 24 '15 01:03

Daniel Morris


2 Answers

Use this format:

suggestion: function(data) {
    return '<p><strong>' + data.value + '</strong> – ' + data.year + '</p>';
}

Taken from this thread.

like image 93
Daniel Morris Avatar answered Nov 08 '22 07:11

Daniel Morris


This might help - I've integrated it with Bootstrap:

<div class="col-lg-3" id="the-basics">
<input type="text" class="typeahead form-control" placeholder="my placeholder" aria-describedby="basic-addon1">
</div>

$('#the-basics .typeahead').typeahead(null, {
  name: 'best-pictures',
  display: 'imageUrl',
  source: function show(q, cb, cba) {
    console.log(q);
    var url = '/yoururl/'+q;
    $.ajax({ url: url })
    .done(function(res) {
      cba(res.list);;
    })
    .fail(function(err) {
      alert(err);
    });
  },
    limit:10,
  templates: {
    empty: [
      '<div class="empty-message">',
        'No data',
      '</div>'
    ].join('\n'),
    suggestion: function(data) {
      return '<p><strong>' + data.itemName + '</strong> - <img height:"50px" width:"50px" src='+data.imageUrl+'></p>';
    }
  }
});
like image 21
Gaurav Sharma Avatar answered Nov 08 '22 07:11

Gaurav Sharma