Skip to content

nunjucks

The nunjucks templating docs are a great way to get started with the templating language.

Includes

Includes allow us to define blocks of repeatable content to be reused.

If you think about something like a summary list we could extract this, and re-use it mutiple times across sevral pages

{% include "summary-list.html" %}

This can help seperate out content, it also inhreits in the next example we can use {{ name }} to output the paramter

{% set name = "Example Name" %}
{% include "summary-list.html" %}

Macros

Macros allow us to create components which encsculate code to be re-used.

The GOV.UK Design system has many examples, with details of each component.

{% from "govuk/components/button/macro.njk" import govukButton %}
{{
govukButton({
text: "Save and continue"
})
}}

We can build new components and share them using the plguin system.

A good example of this is the GOV.UK One Login header.

Components can also be made to wrap other components providing an way to compose mutiple levels of UI.

Extends

Extends allow us to create templates.

GOV.UK Page template provides the ability to build a full GOV.UK page.

We can also override elements of this, for example with the DWP Internal service page.

We want to change both the default header and footer.

  1. Create a new layout (layouts/agent.njk)

  2. Extend a current layout

    {% extends "govuk-prototype-kit/layouts/govuk-branded.njk" %}
  3. Define a a block to overide something

    {% block header %}
    {{
    dwpHeader({
    serviceName: serviceName,
    serviceHref: "/",
    container: true
    })
    }}
    {% endblock %}

We can do this with any block of the parent template, or create new blocks.

Inheritance

In the last example the govuk/template.njk was extended by the govuk-branded.njk template with a new template layouts/agent.njk which can be used in pages.

We can override blocks at any point in the chain.

We can also use the super() function to render the parent block in child block.

If we use our pervious example, we can reuse the base header, and add more too it.

{% block header %}
{{ super() }} // this renders the orginal header
{{
govukPhaseBanner({
tag: {
text: "Alpha"
},
html: 'This is a new service. Help us improve it and <a class="govuk-link" href="#">give your feedback by email</a>.'
})
}}
{% endblock %}