adriaan
adriaan

Reputation: 1118

Use custom helpers in Handlebars which are loaded from an api

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;

Just calling the helper like this

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

When I use this Handlebar this code works fine

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

But when using render, bind-attr, custom-helper,

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

the console logs an error:

Uncaught TypeError: Cannot read property 'container' of null

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

Upvotes: 1

Views: 1111

Answers (1)

adriaan
adriaan

Reputation: 1118

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;

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

Upvotes: 1

Related Questions