How to Add Handlebars Helpers to Pattern Lab

2018-06-08 | #handlebars, #patternlab, #solution

Pattern Lab Node is the go to solution to build living styleguides at the moment and it uses all the cool standard technologies node development currently offers. But for some people the default Mustache templating is a little bit meek and far away from other templating languages, which might especially be a problem when you're writing a proof-of-concept your CMS guys might want to use as a blueprint to implement their CMS templates.

Enter Handlebars, the cozy Mustache alternative adding more programmatic helpers and (especially) the possibility to extend the syntax with own helpers.

Installing the Handlebars template engine is easy enough, just install the prepared package ("patternengine-node-handlebars" for example) next to patternlab-node and change the template extension in the patternlab-config to "hbs". But how do I extend the engine, how do I use stuff like the package "Handlebar Helpers". Well, there's no prepared way to do this, no callback, no config, but the extensibility is one of the main reasons you might want to use Handlebars right?

That's a tough one that took some headscratching and source reading, but the result is quite simple: It turns out you can do that right there in the gulp file, but how is not quite obvious:

const patternlabConfig = require('./patternlab-config.json'),

patternlab = require('patternlab-node')(patternlabConfig),

patternLabEngines = require('./node_modules/patternlab-node/core/lib/pattern_engines');

const handlebars = patternLabEngines.handlebars.engine,

// do not comment or remove next line, instantiation is needed for extension of handlebars!

handlebarsHelpers = require('handlebars-helpers')(['array', 'collection', 'comparison', 'math', 'number', 'object', 'string', 'url'], {handlebars : handlebars});

handlebars.registerHelper('to_string', function(name){

return ''+name;

});

The secret is the fact that the Handlebars requirement behaves as a singleton, returning the exact same reference on repeated requires. So you actually get the same Handlebars reference here, that is used by Pattern Lab beforehand and are free to extend it to your heart's desire.