我可以在Typeahead.js中更改模板引擎吗?

Phi*_*hil 11 javascript jquery typeahead typeahead.js twitter-typeahead

Twitter Typeahead.js 0.10.0现在使用Bloodhound.js与服务器进行交互.

是否有可能将其使用的模板引擎从车把更改为underscore.js'或knockout.js拳击'模板引擎?

Phi*_*hil 17

哦,我对显而易见的事情视而不见.在配置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(''))
  }
});
Run Code Online (Sandbox Code Playgroud)

上面的代码使用了Handlebars.但是您可以使用任何支持编译功能的模板引擎.该编译功能将用户模板并处理它需要是让需要被呈现的HTML.如果要使用下划线,请将其扩展为支持名为"compile"的函数并引用它.说明这一点的代码如下.

;(function (_) {
    'use strict';

    _.compile = function (templ) {
        var compiled = this.template(templ);
        compiled.render = function (ctx) {
            return this(ctx);
        }
        return compiled;
    }
})(window._);
Run Code Online (Sandbox Code Playgroud)

我从Alan Greenblatt得到了这个.链接是:http://blattchat.com/2013/06/04/twitter-bootstrap-typeahead-js-with-underscore-js-tutorial.他的推特类型的例子是过时的,因为他们是为twitter类型0.9.3缺乏bloodhound.js.但是,它确实为下划线模板引擎提供了一个很好的编译功能.

现在,使用下划线模板,代码将如下所示:

$('.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(''))
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 不是马上,抱歉.这只是'建议:_.template(`.无论如何它们都返回函数,typeahead不会看到**_.compile**和**_.template**之间的区别.干杯 (3认同)
  • 似乎只使用`_.template()`也可以. (2认同)

mde*_*dev 11

好消息是,如Steve Pavarno所述,您不再需要模板引擎了.您可以通过传递如下函数来实现所需的结果:

// ...
templates: {
    suggestion: function(data) { // data is an object as returned by suggestion engine
        return '<div class="tt-suggest-page">' + data.value + '</div>';
    };
}
Run Code Online (Sandbox Code Playgroud)