Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handlebars with Express: different html head for different pages

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}}}.)

like image 463
user3303012 Avatar asked Feb 12 '14 18:02

user3303012


People also ask

How do you use express handlebars?

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.

Why should I use handlebars?

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.

Which syntax is used to specify a partial handlebars file that should be included in a location when the page is requested?

In order to use a partial, it must be registered via Handlebars. registerPartial . Handlebars. registerPartial('myPartial', '{{prefix}}');


1 Answers

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> 
like image 157
Ethan Brown Avatar answered Oct 04 '22 01:10

Ethan Brown