Handlebars with Express: different html head for different pages

This is a great question and, in my mind, a glaring weakness in Express’s view model. Fortunately, there is a solution: use Handlebars block helpers. Here’s the helper I use for this purpose:

helpers: {
    section: function(name, options){
        if(!this._sections) this._sections = {};
        this._sections[name] = options.fn(this);
        return null;
    }
}

Then, in your layout, you can do the following:

<head>
    {{{_sections.head}}}
</head>
<body>
    {{{body}}}
</body>

And in your view:

{{#section 'head'}}
    <!-- stuff that goes in head...example: -->
    <meta name="robots" content="noindex">
{{/section}}

<h1>Body Blah Blah</h1>
<p>This goes in page body.</p>

Leave a Comment