Create layout with HandlebarsJS

Create layout with HandlebarsJS

Layout template is a good practice following the DRY (Don't Repeat Yourself) principle. This file contains the skeleton of the pages and the remaining templates will only add the content to the skeleton. In most of the cases, the layout contains the HTML skeleton with the main CSS, JS, Fonts files, but also some main UI components like the header, footer, the navigation bar.

Handlebars templates engine does not provides layout feature out of the box but it still be possible to create a layout with Partial Blocks like the following code.

First, create a layout template with Partial Blocks slot. You can have one or several additional variables.

<!DOCTYPE html>
<html lang="en">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="/css/main.css">

{{> @partial-block }}

Then, use it as a Partial Block.

{{#> layout title='Homepage' }}
<h1>Welcome to my website</h1>
<p>This is the home page</p>
Share this post
Follow the RSS feed

Subscribe to the newsletter

Get emails from me about web development and a lot of topics related to tech.