【发布时间】:2014-02-28 18:36:04
【问题描述】:
twitter typeahead.js 0.10.0现在使用bloodhound.js与服务器进行交互。
是否可以将它使用的模板引擎从车把更改为 underscore.js 或 knockout.js 拳头的模板引擎?
【问题讨论】:
标签: javascript jquery typeahead typeahead.js twitter-typeahead
twitter typeahead.js 0.10.0现在使用bloodhound.js与服务器进行交互。
是否可以将它使用的模板引擎从车把更改为 underscore.js 或 knockout.js 拳头的模板引擎?
【问题讨论】:
标签: javascript jquery typeahead typeahead.js twitter-typeahead
哦,我对显而易见的事情视而不见。在配置 twitter typeahead 时,在 templates 选项中,在 suggestion 子选项中;在那里你可以选择你的视图引擎。举例说明(取自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 功能的模板引擎。 compile 函数获取用户模板并根据需要对其进行处理以获取需要呈现的 HTML。如果您想使用下划线,请将其扩展为支持名为“compile”的函数并引用它。 说明这一点的代码如下。
;(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(''))
}
});
【讨论】:
_.template() 也可以。
suggestion: _.template(。无论如何,它们都返回函数,typeahead 不会看到 .compile 和 .template 之间的区别。干杯
Hogan.compile(...) 但这不起作用。如果您有解决方案,请参阅stackoverflow.com/questions/24727534/… -- 谢谢!
好消息是,正如 Steve Pavarno 所说,您不再需要模板引擎。您可以通过传递这样的函数来实现所需的结果:
// ...
templates: {
suggestion: function(data) { // data is an object as returned by suggestion engine
return '<div class="tt-suggest-page">' + data.value + '</div>';
};
}
【讨论】: