Search code examples
javascriptnode.jshandlebars.jsassemblegrunt-assemble

Register Assemble Handlebars Helpers


I am trying to do something that seems relatively simple from the Assemble docs and other repos I've looked at but for some reason I'm having a problem registering my Handlebars helpers. The helper is in helpers > helper-classgrid.js

module.exports.register = function (Handlebars, options, params)  { 
  Handlebars.register('classgrid', function (index, options)  { 
    gridclass: function (index, options) {
    if (index === 0 || index % 4 === 0) {
        return options.fn(this);
      }
    return options.inverse(this);
  };
};

My gruntfile where config.helpers = helpers:

assemble: {
      options: {
        layoutdir: '<%= config.guts %>/templates/layouts/',
        assetsDir: '<%= grunt.config.get("assets_dir") %>',
        environmentIsProduction: '<%= grunt.config.get("environmentIsProduction") %>',
        environmentIsDev: '<%= grunt.config.get("environmentIsDev") %>',
        data: ['<%= config.content %>/**/*.json', '<%= grunt.config.get("environmentData") %>'],
        helpers: ['<%= config.helpers %>/helper-*.js']
      },
}

Template code:

{{#classgrid @index}}
// do something here
{{/classgrid}}

Now when I implement my helper in my Handlerbars template and run the grunt task containing the assemble task I get the error

Warning: Missing helper: 'classgrid' Use --force to continue.

I'm not sure what I've done wrong or if I have to create a separate NPM package for my helpers which it seems to suggest in the assemble docs. I've looked at these 2 repos which seem to be doing what I'm trying to do

https://github.com/buildingblocks/bb-prototype-website/blob/master/Gruntfile.js https://github.com/ghost-town/layouts-example/blob/master/Gruntfile.js#L33


Solution

  • Not sure if this was just a copy/paste issue, but the code above doesn't look correct... here's what should work:

    module.exports.register = function (Handlebars, opts, params)  { 
      Handlebars.registerHelper('classgrid', function (index, options)  { 
        if (index === 0 || index % 4 === 0) {
          return options.fn(this);
        }
        return options.inverse(this);
      });
    };
    

    I'll try to create a test project to make sure this is working.

    Edit: After creating a test project, I see that you were using Handlebars.register instead of Handlebars.registerHelper. I've updated the code to a working solution. Hope this helps.