【问题标题】:how to use Twitter typeahead.js with Jsrender compile function如何使用带有 Jsrender 编译功能的 Twitter typeahead.js
【发布时间】:2014-10-03 22:43:39
【问题描述】:

typeahead.js 文档展示了使用 Hogan.js 的示例,但我将使用 Jsrender 模板。任何模板引擎都可以使用,只要它支持预期的 API。 有使用 Underscore.js 模板的示例。 下面是使用 Underscore.js 的配置示例,通过在文档准备好时执行以下 JavaScript 来支持这一点:

 $(function($) {    
      _.compile = function(templ) {
         var compiled = this.template(templ);
         compiled.render = function(ctx) {
            return this(ctx);
         }
         return compiled;
      }
      $('.product-typeahead').typeahead({
         header: '<h3>Products</h3>',
         template: 
       '<p><strong><%= name %></strong>:&nbsp;$<%= price %></p>',
         name: 'products',
         valueKey: 'name',
         engine: _,
         local: [
            {
               id: 0,
               name: "Deluxe Bicycle",
               price: 499.98
            },
            {
               id: 1,
               name: "Super Deluxe Trampoline",
               price: 134.99
            },
            {
               id: 2,
               name: "Super Duper Scooter",
               price: 49.95
            }
         ]
      }).on('typeahead:selected', function(event, datum) {
         $('#productID').val(datum.id);
         $('#productPrice').val("$" + datum.price);
      });
   });

我需要使用 JSrender 模板引擎实现上述打字头自动完成功能。我尝试了作者 Boris Moore 在https://github.com/BorisMoore/jsrender/issues/30 提供的解决方案。如何使用 jsRender 实现这一点? 提前致谢。

【问题讨论】:

    标签: twitter-bootstrap template-engine jquery-templates jsrender


    【解决方案1】:

    您尝试过吗 - 将 $.templates 包装为您的引擎:

    var jsRenderEngine = {
          compile: $.templates
       };
    
    $('.product-typeahead').typeahead({
       ...
       engine: jsRenderEngine,
       local: [
          ...
       ]
    }).on('typeahead:selected', function(event, datum) {
       ...
    });
    

    或者扩展 $.templates 以使其成为您的引擎 - 使其成为自己的“编译”方法!:

    $.templates.compile = $.templates;
    
    $('.product-typeahead').typeahead({
       ...
       engine: $.templates,
       local: [
          ...
       ]
    }).on('typeahead:selected', function(event, datum) {
       ...
    });
    

    【讨论】:

    • @MikMark:我在上面添加了另一种方法。你能确认它是否也有效吗?
    • 好的 - 我现在已经从我的答案中删除了它。谢谢。
    猜你喜欢
    • 2013-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多