Handlebars with Express: different html head for different pages

user3303012 picture user3303012 · Feb 12, 2014 · Viewed 11.8k times · Source

I am using Handlebars in an Express Node.js app. My layout.html file includes a <head> section. How can I make the <head> section different for different pages? (So that I can, for example, reference a JavaScript file in only one page, and vary the <title> for each page.)

layout.html looks like this:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script src='/public/ajsfile.js'></script>
    <link type='text/css' href="/public/style.css" rel="stylesheet">
  </head>
  <body>
    {{{body}}}
  </body>
</html>

(I am imagining varying the <head> content with something analogous to {{{body}}} in the above, but with {{{head}}}.)

Answer

Ethan Brown picture Ethan Brown · Feb 12, 2014

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>