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}}}
.)
To use handlebars in express, we need to store HTML code into a . hbs extension in the 'views' folder in the source directory as hbs looks for the pages in the views folder. Now, we need to change the default view engine. Now, we render our webpage through express to the local server.
Handlebars is a pure rendering engine. It works well if you want to allow people to write templates for rendering HTML-pages, e-mails or markdown files. It has no built-in support for event-handling, accessing backend-services or incremental DOM updates.
In order to use a partial, it must be registered via Handlebars. registerPartial . Handlebars. registerPartial('myPartial', '{{prefix}}');
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With