Search code examples
htmlhandlebars.js

How to include header and footer in HTML files using handlebars


I would like to include header.html and footer.html in every HTML pages of my website using Handlebars. I've done some tutorials about Handlebars so I know how to include some text but I didn't find how to include a file.

Do you know if I can do that with Handlebars and how?


Solution

  • What you are looking for are handlebars partials.

    Handlebars allows for template reuse through partials. Partials are normal Handlebars templates that may be called directly by other templates.

    Basic example:

    In order to use a partial, it must be registered via Handlebars.registerPartial().

    Handlebars.registerPartial('myPartial', '{{name}}');
    

    This call will register the myPartial partial. Partials may be precompiled and the precompiled template passed into the second parameter. Calling the partial is done through the partial call syntax:

    {{> myPartial }}
    

    Will render the partial named myPartial. When the partial executes, it will be run under the current execution context.