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.
Part of Web servers
- Create your serverP
- Create your appP
- Node and the terminalP
- More about the terminalP
- Web frameworksP
- Using ExpressP
- Serving static files
- Views and templates
- Routing
- Real data
- Includes
- Get confident with Express
- Build your app in ExpressP