How to Register custom handelbars helper in assemble 0.17.1

178 views Asked by At

In my assemblefile.js I try to register a custom helper. The helper itself does work since i have it in use in a grunt project with assemble.

assemble: {
  options: {
    helpers: ['./src/helper/custom-helper.js' ]
  }
}

In assemble 0.17.1 I tried it like this but it doesn´t work. Does anyone know how to do this?

app.helpers('./src/helper/custom-helper.js');

custom-helper.js:

module.exports.register = function (Handlebars, options, params)  {

    Handlebars.registerHelper('section', function(name, options) {
        if (!this.sections) {
        this.sections = {};
    }
    this.sections[name] = options.fn(this);
    return null;;
    });

};
1

There are 1 answers

0
doowb On BEST ANSWER

assemble is built on top of the templates module now, so you can use the .helper and .helpers methods for registering helpers with assemble, which will register them with Handlebars. This link has more information on registering the helpers.

Since the templates api is used, you don't have to wrap the helpers with the .register method in your example. You can just export the helper function, then name it when registering with assemble like this:

// custom-helper.js
module.exports = function(name, options) {
  if (!this.sections) {
    this.sections = {};
  }
  this.sections[name] = options.fn(this);
  return null;
};

// register with assemble
var app = assemble();
app.helper('section', require('./custom-helper.js'));

You may also export an object with helpers and register them all at once using the .helpers method:

// my-helpers.js
module.exports = {
  foo: function(str) { return 'FOO: ' + str; },
  bar: function(str) { return 'BAR: ' + str; },
  baz: function(str) { return 'BAZ: ' + str; }
};

// register with assemble
var app = assemble();
app.helpers(require('./my-helpers.js'));

When registering the object with the .helpers method, the property keys are used for the helper names