01 Project – Node.js / Express / MongoDB – Part 08 – Creating the main.handlebars file layout

When you build a website you would want to have a layout (template) used by every page. This layout should contain a header with title, logo etc, a navigation bar (if the developer needs a navigation bar), and a footer to contain the copyright information and maybe other information. Handlebars helps you with this matter!

Let’s create a layout file for our application by creating a new file named main.handlebars within the views/layouts folder. Insert the following code in it:

<!DOCTYPE HTML>
<html lang="en">
<head>
  <title>Project2Img</title>

  

<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
  <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="/public/css/styles.css">
</head>
<body>
  <div class="page-header">
    <div class="container">
      <div class="col-md-6"><h1><a href="/">Project2Img</a></h1></div>
    </div>
  </div>
  <div class="container">
    <div class="row">
      <div class="col-sm-8">{{{ body }}}</div>
      <div class="col-sm-4">{{> stats this }}{{> popular this }}{{> comments this }}</div>
    </div>
  </div>
  <div style="border-top: solid 1px #eee; padding-top: 1em;">
    <div class="container">
      <div class="row">
        <div class="col-sm-12 text-center">
          <p class="text-muted">Project2Img | &copy; Copyright 2017, All Rights Reserved</p>
          <p class="text-center">
            <i class="fa fa-twitter-square fa-2x text-primary"></i><i class="fa fa-facebook-square fa-2x text-primary"></i></p>
        </div>
      </div>
    </div>
  </div>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script type="text/javascript" src="/public/js/scripts.js"></script>
</body>
</html>

As you can see most of the code is HTML. It uses Bootstrap, but not only, for the actual layout display.

Somewhere at the middle of the code you can see {{{ body }}} which is a reserved word in Handlebars, used with layouts. Basically, the content will be inserted in {{{ body }}} area.

You might ask yourself why are there three parentheses around the body. In order to avoid Handlebars to escape the HTML that will be inserted in the body area we use three parentheses instead of two.

Below {{{ body }}} you can see {{ > … }}. It renders Handlebars partials.

Leave a Reply