Twitter Typeahead.js 0.10.0 现在使用 Bloodhound.js 与服务器交互。
是否可以将它使用的模板引擎从车把更改为 underscore.js 或 knockout.js 打孔的模板引擎?
Twitter Typeahead.js 0.10.0 现在使用 Bloodhound.js 与服务器交互。
是否可以将它使用的模板引擎从车把更改为 underscore.js 或 knockout.js 打孔的模板引擎?
哦,我对显而易见的事情视而不见。在配置 twitter typeahead 中,在模板选项中,在建议子选项中;在那里你可以选择你的视图引擎。为了说明(取自http://twitter.github.io/typeahead.js/examples/):
$('.example-twitter-oss .typeahead').typeahead(null, {
name: 'twitter-oss',
displayKey: 'name',
source: repos.ttAdapter(),
templates: {
suggestion: Handlebars.compile([
'<p class="repo-language">{{language}}</p>',
'<p class="repo-name">{{name}}</p>',
'<p class="repo-description">{{description}}</p>'
].join(''))
}
});
上面的代码使用 Handlebars。但是您可以使用任何支持编译功能的模板引擎。compile 函数获取用户模板并根据需要对其进行处理以获取需要呈现的 HTML。如果要使用下划线,请将其扩展为支持名为“编译”的函数并引用它。说明这一点的代码如下。
;(function (_) {
'use strict';
_.compile = function (templ) {
var compiled = this.template(templ);
compiled.render = function (ctx) {
return this(ctx);
}
return compiled;
}
})(window._);
我从艾伦格林布拉特那里得到这个。链接是:http ://blattchat.com/2013/06/04/twitter-bootstrap-typeahead-js-with-underscore-js-tutorial 。他的 twitter typeahead 示例过时了,因为它们是为缺少 bloodhound.js 的 twitter typeahead 版本 0.9.3 制作的。但是,它确实为下划线模板引擎提供了一个很好的编译功能。
现在,使用下划线模板,代码将如下所示:
$('.example-twitter-oss .typeahead').typeahead(null, {
name: 'twitter-oss',
displayKey: 'name',
source: repos.ttAdapter(),
templates: {
suggestion: _.compile([
'<p class="repo-language"><%=language%></p>',
'<p class="repo-name"><%=name%></p>',
'<p class="repo-description"><%=description%></p>'
].join(''))
}
});
好消息是,正如 Steve Pavarno 所说,您不再需要模板引擎。您可以通过传递如下函数来实现所需的结果:
// ...
templates: {
suggestion: function(data) { // data is an object as returned by suggestion engine
return '<div class="tt-suggest-page">' + data.value + '</div>';
};
}