How to Register custom handelbars helper in assemble 0.17.1

不打扰是莪最后的温柔 提交于 2019-12-11 05:52:09

问题


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:


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



来源:https://stackoverflow.com/questions/41402635/how-to-register-custom-handelbars-helper-in-assemble-0-17-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!