Nunjucks tutorial

Server-rendert macros for Eleventy, Express, or onie Node templating pipeline — the GOV.UK-style approach, wi Lily's catalog an class hooks.

Whit ye'll big

A wee server-rendert contact form — labelled input, submit button, zero JavaScript payload — first bare, then styled, in aboot 10 minutes.

Afore ye stairt

Ye need git, Node 22 or later, an pnpm 10 or later. Onie Nunjucks pipeline wirks — Eleventy, Express, or plain Nunjucks.

Step 1 — Git the code

git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-nunjucks-headless
pnpm install
pnpm test        # vitest rendering every macro

Ilka component is a directory in components/ wi a macro.njk, its test, an its docs — for example components/button/macro.njk. Pynt yer Nunjucks loader at components/ (in Eleventy, add it tae the includes path) an import whit ye need.

Step 2 — Yer first component

{% from "components/button/macro.njk" import button %}

{{ button({ text: "Save", type: "submit" }) }}

Renders <button class="button" type="submit">Save</button>. Macros tak a single params object: text (escapit) or html (raw), type, label for an aria-label, an a class hook appender.

Step 3 — Compose a wee form

{% from "components/form/macro.njk" import form %}
{% from "components/label/macro.njk" import label %}
{% from "components/text-input/macro.njk" import textInput %}
{% from "components/button/macro.njk" import button %}

<form class="form" method="post">
  <div class="field">
    {{ label({ for: "name", text: "Full name" }) }}
    {{ textInput({ id: "name", name: "name", required: true }) }}
  </div>
  {{ button({ text: "Save", type: "submit" }) }}
</form>

Because aathing renders on the server, the browser receives pure semantic HTML wi the class hooks — a JavaScript payload o zero bytes.

Check yer wirk: load the page an the form looks plain — exactly as intendit: styling is still aheid. Press Tab: focus muives through ilka control, the label is announced, an submit wirks. The behaviour is deen; the look is yours, an it's neist.

Step 4 — Style it

Style the hooks — .button, .text-input, .label, .field — in yer stylesheet, or link a ready-made theme in yer base layoot:

<link rel="stylesheet" href="/themes/united-kingdom-government-digital-service.css" />

Step 5 — See it aw wirkin

The Nunjucks + Eleventy example app bigs the full catalog as a static site wi per-component demo pages:

git clone https://github.com/LilyDesignSystem/lily-design-system
cd lily-design-system/lily-design-system-nunjucks-eleventy-examples
pnpm install && pnpm run dev

Neist steps

Questions alang the wey? The help page is fu o answers — an if a step could be clearer, tell us an we'll gladly improve the tutorial.