【问题标题】:Use custom helpers in Handlebars which are loaded from an api在从 api 加载的 Handlebars 中使用自定义助手
【发布时间】:2014-09-17 06:54:52
【问题描述】:

通过 ember-cli,我使用了一些从 api 加载的把手。我在 Handlebars 模板中使用变量,但现在最好让 renderbind-attrcustom-helper 工作。

// app/helpers/view-helper.js
var ViewTemplateHelper = Ember.Handlebars.makeBoundHelper(function(template, context) {

  if (Ember.isEmpty(template)) {
    return;
  }
  else if (Ember.isArray(template)) {
    template = template.get('firstObject.value');
  }
  else {
    template = template.get('value');
  }

  context = context || this;

  var dummy = Ember.View.extend({
    classNames: ['view-template'],
    context: context,
    template: Ember.Handlebars.compile(template)
  });

  var view = dummy.create();
  var $elem = null;

  Ember.run(function() {
    $elem = $('<div>');
    view.appendTo($elem);
  });

  return new Ember.Handlebars.SafeString($elem.html());
});

export default ViewTemplateHelper;

像这样调用助手

// app/templates/blog-list.hbs
{{view-template blog}}

当我使用这个 Handlebar 时,这段代码可以正常工作

<h1>{{blog.title}}</h1>

但是当使用renderbind-attrcustom-helper

{{render 'blog/cover' blog.image}}

控制台记录错误:

Uncaught TypeError: Cannot read property 'container' of null

有谁知道如何在从 api 加载的 Handlebars 中使用自定义帮助器?

【问题讨论】:

    标签: javascript ember.js handlebars.js


    【解决方案1】:

    解决方案是使用此代码

      options.hash.content = template;
      return Ember.Handlebars.helpers.view.call(this, view, options);
    

    完整的助手

    var ViewTemplateHelper = Ember.Handlebars.makeBoundHelper(function(template, options) {
    
      if (Ember.isEmpty(template)) {
        return;
      }
      else if (Ember.isArray(template)) {
        template = template.get('firstObject.value');
      }
      else {
        template = template.get('value');
      }
    
      var dummy = Ember.View.extend({
        classNames: ['view-template'],
        template: Ember.Handlebars.compile(template)
      });
    
      var view = dummy.create();
    
      options.hash.content = template;
      return Ember.Handlebars.helpers.view.call(this, view, options);
    });
    
    export default ViewTemplateHelper;
    

    感谢http://discuss.emberjs.com/t/how-do-you-render-a-view-from-within-a-handlebars-helper-that-takes-dynamic-content/984/3?u=harianus

    【讨论】:

      猜你喜欢
      • 2013-06-27
      • 2016-06-09
      • 1970-01-01
      • 2016-12-04
      • 2023-03-30
      • 2018-05-14
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      相关资源
      最近更新 更多