Download

How to create custom Handlebars helpers?

When creating your theme you may want to expand the number of helpers; Publii offers theme developers the ability to create custom helpers for their needs. They're handy if you need to simplify your theme code.

E.g. you can create a custom helper which will replace multiple conditions with a single conditional check.

To create custom helpers in your theme just create a helpers.js file in the theme directory; here you can add your custom helper functions.

Below there is an example of code which creates two super simple custom helpers which accept one argument:

/*
 * Custom theme helpers for Handlebars.js
 */

let themeHelpers = {
    test1: function(value) {
        return "TEST1 " + value;
    },
    test2: function(value) {
        return "TEST2 " + value;
    }
};

module.exports = themeHelpers;

As you can see - all helper functions are wrapped inside an object which is exported from the helpers.js file to the renderer.

It is also possible to use Handlebars object instance - This scenario will require field includeHandlebarsInHelpers set to true under renderer section in the theme settings.

Then helpers.js file can be written as:

module.exports = function (Handlebars) {
	return {
	    functionName: function(arg) {
	        // ...
	        return new Handlebars.SafeString(arg);
	    }
	};
  };

What are you waiting for?

Start building your site today.

  1. 1 Download Publii
  2. 2 Write your content
  3. 3 Publish your site
Create website