Use MoJ Frontend Nunjucks
You can use our Nunjucks code to generate the HTML for pages and components.
You can also change the HTML that’s generated by passing options into the Nunjucks code.
If you use Nunjucks, your application will be easier to update when a new version of MoJ Frontend is released.
To use Nunjucks, your application and any frameworks that support your application must use Node.js.
You do not need to follow this guidance to set up coded prototypes using the GOV.UK Prototype Kit.
Before you start
You must first:
- install MoJ Frontend with Node.js package manager (npm)
- make sure you’ve installed Nunjucks so it’s working in your environment
Set up Nunjucks and use the page template
-
Add both
node_modules/@ministryofjustice/frontend
andnode_modules/govuk-frontend/dist
to your list of Nunjucks paths, so Nunjucks knows where to find templates and components from MoJ Frontend and GOV.UK Frontend.For example:
nunjucks.configure([ 'node_modules/@ministryofjustice/frontend', 'node_modules/govuk-frontend/dist', '<YOUR-VIEWS-FOLDER>' ]);
-
Use the MoJ Frontend template by adding the following at the top of your view file:
{% extends "moj/template.njk" %}
You may need to change the paths in the Nunjucks code to get the CSS, assets and JavaScript working.
Find out how to change template content.
Adding Nunjucks filters
You will need to install the MoJ Frontend Nunjucks filters to use the messages and timeline component macros:
-
Import the filters
import mojFilters from '@ministryofjustice/frontend/moj/filters/all.js'
-
Add the filters to your Nunjucks environment
for (const [name, filter] of Object.entries(mojFilters())) { nunjucksAppEnv.addFilter(name, filter) }
Adding a component
Go to any component page on the MoJ Design System website, then copy the Nunjucks macro code from the Nunjucks tab of any example.
For example, to add the button menu component to your page, copy the code from the Nunjucks tab in the first example on the button menu component page.
Configuring a component
You can use options to configure how a component looks or behaves.
For example, use the text
option to configure the text on a notification badge:
{{ mojNotificationBadge({
text: "10"
}) }}
To see the options for a component, go to any component page on the Design System website, select the Nunjucks tab of an example, then select Nunjucks macro options.
You must sanitise any HTML you pass in to Nunjucks macros you’re using in your live application to protect your website against cross-site scripting (XSS) attacks. You can read more about XSS on the MDN website.