A lightweight wrapper around the popular Handlebars library to add support for nested layouts.
The package can be installed with the following command:
npm install handlebars-extended --save
The example below shows how a Handlebars content page can be nested within a layout.
var hbx = require('handlebars-extended');
// register the global layout
hbx.registerLayout('root', '<FROM ROOT.HBS>');
// compile the content page template
var template = hbx.compile('<FROM WELCOME.HBS>');
// render the nested content page with data
var result = template({ title: 'Why hello there!', question: 'How is your day going?' });
<html>
<head><title>Why hello there!</title>
<body>
<h1>Welcome page</h1>
How is your day going?
</body>
</html>
The layout definition is a Handlebars comment that defines the name of the layout that should be used. By using comments, the definition will be ignored if by the standard Handlebars project.
Layouts can also define layout definitions meaning multiple layers of nest are possible.
In order to maintain existing handlebars functionality, HBX monkey patches the
existing compile
method. Currently the precompile
method has been disabled.
Registers a global layout that can then be used by all future compile
calls.
hbx.registerLayout('root', '<div>{{{content}}}</div>');
Removes a registered global layout, this will result in the layout no longer being available
to any past or future compile
calls.
hbx.unregisterLayout('root');
Local layouts can also be specified when rendering a template, just like partials and helpers in Handlebars.
var template = hbx.compile('{{! layout: root }}\nhello');
template({ layouts: { root: '<div>{{{content}}}</div>' } });