【问题标题】:Can I change the templating engine in Typeahead.js?我可以更改 Typeahead.js 中的模板引擎吗?
【发布时间】: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


    【解决方案1】:

    哦,我对显而易见的事情视而不见。在配置 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() 也可以。
    • @luwes:感谢您提供的信息。你手边有 jsFiddle 吗?
    • 不是马上,抱歉。只是suggestion: _.template(。无论如何,它们都返回函数,typeahead 不会看到 .compile.template 之间的区别。干杯
    • 知道如何让它与 Hogan 一起工作吗?我试过Hogan.compile(...) 但这不起作用。如果您有解决方案,请参阅stackoverflow.com/questions/24727534/… -- 谢谢!
    • 有没有使用knockoutjs模板的例子?
    【解决方案2】:

    好消息是,正如 Steve Pavarno 所说,您不再需要模板引擎。您可以通过传递这样的函数来实现所需的结果:

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

    【讨论】:

    • 太棒了!这比使用模板引擎更有用。
    猜你喜欢
    • 1970-01-01
    • 2018-07-07
    • 2017-03-09
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多