[NJS] Layouts

:  ~ 1 min read

Express 2.0 apparently had layouts and partials included, but they were removed in 3.0. Luckily, ejs-mate has us covered.

Let's quickly cover partials, because it feels a bit easier. First, the partial, inside an example.ejs file, located in the same views folder where all your views are kept (preferably inside a nested partials folder):

<p>I am a partial</p>
And I will be included too

Then, when we want this bit of code in another file, we can just include it where it's needed:

<h1>About me</h1>
<% include ./partials/example >
More stuff here

This will be rendered as:

<h1>About me</h1>
<p>I am a partial</p>
And I will be included too
More stuff here

Partials are really handy when you have bits of code that will be used in several places. But what about layouts? You can define a whole layout, common to different pages: using my website as an example, here's the layout.ejs file:

<!DOCTYPE html>
<html>
<head>
  <% include ./partials/head %>
  <%- block('head') %>
</head>
<body>
  <% include ./partials/header %>
  <%- body %>
  <% include ./partials/footer %>
</body>
</html>

Here we see the head, the header (navigation) and the footer as partials, like we discussed above; these are common for all pages. To quickly explain the two foreign calls, <%- block('head') >, and <%- body >, I'll just paste in my 404 page:

<% layout('layout') %>
<% block('head').append('<link rel="stylesheet" href="/assets/sections/404.css">') %>
<h1 class="the-404"><span class="the-404">404</span></h1>
<p class="error-message">This isn't the page you are looking for.</p>

All of this means "take layout.ejs, replace <%- body > with the code in this file (except any layout handling, of course), and replace <%- block('head') > with the string from the .append call(s)", thus the 404 page will render like this:

<!DOCTYPE html>
<html>
<head>
  // Everything inside head partial
  // Our 404 styles:
  <link rel="stylesheet" href="/assets/sections/404.css">
</head>
<body>
  // Everything inside the header partial  
  // Our 404 "body":
  <h1 class="the-404"><span class="the-404">404</span></h1>
  <p class="error-message">This isn't the page you are looking for.</p>
  // Everything inside the footer partial
</body>
</html>