Typeahead自定义模板,无Handlebars

时间:2015-03-24 01:32:57

标签: jquery typeahead.js

我正在尝试实施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>')
  }
});

特别是这一行:

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

最初我没有意识到你需要明确要求Handlebars作为依赖:

Uncaught ReferenceError: Handlebars is not defined

当我删除Handlebars时......

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

它给出了另一个JS错误:

Uncaught ReferenceError: value is not defined

是否可以在不使用Handlebars引擎的情况下使用自定义视图模板?

2 个答案:

答案 0 :(得分:55)

使用以下格式:

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

取自this thread

答案 1 :(得分:3)

这可能有所帮助 - 我已将其与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>';
    }
  }
});