在从api加载的Handlebars中使用自定义助手 [英] Use custom helpers in Handlebars which are loaded from an api

查看:98
本文介绍了在从api加载的Handlebars中使用自定义助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ember-cli我使用一些从api加载的句柄。我在Handlebars模板中使用了变量,但现在可以很好地获取 render bind-attr custom-helper working。

With ember-cli I use some handlebars which are loaded from an api. I'm using variables in the Handlebars templates, but now it would be nice to get render, bind-attr and a custom-helper working.

// 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}}

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

When I use this Handlebar this code works fine

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

但是当使用 render bind-attr custom-helper

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

控制台记录一个错误:

the console logs an error:

Uncaught TypeError: Cannot read property 'container' of null

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

Does anyone know how to use custom helpers in the Handlebars loaded from the api?

推荐答案

解决方案是使用此代码

The solution was to use this code

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

完整的帮手

The full helper

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

这篇关于在从api加载的Handlebars中使用自定义助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆