Skip to content

Commit 85161b6

Browse files
Documentation for nunjucks functions
1 parent 8215589 commit 85161b6

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

docs/v13/documentation/functions.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
---
2+
heading: Use functions to change how answers appear
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 apply functions.
8+
9+
You can create your own 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+
{{ lastCharacters(data['phone-number'], 4) }}
32+
```
33+
34+
### Use HTML in a Nunjucks function
35+
36+
If you want to use HTML in a function, use the `renderAsHTML` option like this:
37+
38+
```
39+
addfunction('lastCharactersBold', function (text, count) {
40+
return '<strong>' + text.substring(text.length - count) + '</strong>'
41+
}, { renderAsHtml: true })
42+
```
43+
44+
Then use it on a page like this:
45+
46+
```
47+
{{ lastCharactersBold(data['phone-number'], 4) }}
48+
```

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

+3
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 functions to change how answers appear</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)