BETAThis is a new service – your feedback will help us to improve it.

Includes

Often, we will want to reuse parts of a webpage on other webpages.

Most websites have a header and footer that are very similar on all pages of the site. GOV.UK is no exception.

In plain HTML, this is hard to do. Every new webpage needs to be written in full, even if most of the page isn't unique.

If our header or footer needs to change, we would have to make that change in many files.

Nunjucks solves this problem with a feature called includes.

Keep includes organised

To save confusion, we should keep all includes (parts of pages) separate from the full view templates we've used so far.

Create a subfolder of /views called /includes. Create a file called header.njk.

We're going to use this include at the top of every page in our app, so let's give it our app's title and a menu:

<header>
  <h1>My App</h1>
  <nav>
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about">About</a></li>
    </ul>
  </nav>
</header>

Now go to your index.njk view template, and add the following line to the top of the file:

{% include "includes/header.njk" %}

Do the same in the about.njk file.

When a user requests the view, this tag is replaced by the HTML from the file it references.

Restart your app and check the results in the browser. You should see the same header on both pages.

Use this same approach to give your app a footer. Referring to your prototypes, decide what includes your own app will need to make use of.
Lessons last updated 12th July 2019. You can improve this lesson on Github.
Part of Web servers
  1. Create your serverP
  2. Create your appP
  3. Node and the terminalP
  4. More about the terminalP
  5. Web frameworksP
  6. Using ExpressP
  7. Serving static files
  8. Views and templates
  9. Routing
  10. Real data
  11. Includes
  12. Get confident with Express
  13. Build your app in ExpressP