Skip to content

Commit aaea6d6

Browse files
Documentation for nunjucks functions
1 parent 8215589 commit aaea6d6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

docs/v13/documentation/functions.md

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
---
2+
heading: Use a function to change how an answer appears
3+
---
4+
5+
> To use functions, you need to know how to [pass data from page to page](./pass-data).
6+
7+
The kit stores data from all answers that users give in a prototype, so that you can use or show the answers later. To change the format of how these answers appear, you can use a function.
8+
9+
You can create a function to process your data. For example, this function will return the last "count" characters as follows:
10+
11+
```
12+
{{ lastCharacters(data['phone-number'], 4) }}
13+
```
14+
15+
### Create a Nunjucks function
16+
17+
Add your own functions to the `app/functions.js` file. Functions are written in JavaScript.
18+
19+
```
20+
const govukPrototypeKit = require('govuk-prototype-kit')
21+
const addFunction = govukPrototypeKit.views.addFunction
22+
23+
addFunction('lastCharacters', function (text, count) {
24+
return text.substring(text.length - count)
25+
})
26+
```
27+
28+
Then use it on a page like this:
29+
30+
```
31+
<p>
32+
The last 4 numbers in your telephone number are {{ lastCharacters(data['phone-number'], 4) }}
33+
</p>
34+
```
35+
36+
### Use HTML in a Nunjucks function
37+
38+
If you want to use HTML in a function, use the `renderAsHTML` option like this:
39+
40+
```
41+
addFunction('lastCharactersBold', function (text, count) {
42+
return '<strong>' + text.substring(text.length - count) + '</strong>'
43+
}, { renderAsHtml: true })
44+
```
45+
46+
Then use it on a page like this:
47+
48+
```
49+
<p>
50+
The last 4 numbers in your telephone number are {{ lastCharactersBold(data['phone-number'], 4) }}
51+
</p>
52+
```

docs/v13/views/tutorials-and-guides.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,9 @@ <h3 class="govuk-heading-s">Advanced usage</h3>
154154
<li>
155155
<a href="./date-filters">Use filters to add dates</a>
156156
</li>
157+
<li>
158+
<a href="./functions">Use a function to change how an answer appears</a>
159+
</li>
157160
<li>
158161
<a href="./examples/override-service-name">Change the service name on one page</a>
159162
</li>

0 commit comments

Comments
 (0)