Skip to content

Commit

Permalink
Documentation for nunjucks functions
Browse files Browse the repository at this point in the history
  • Loading branch information
BenSurgisonGDS committed Nov 16, 2023
1 parent 8215589 commit 85161b6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
48 changes: 48 additions & 0 deletions docs/v13/documentation/functions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
heading: Use functions to change how answers appear
---

> To use functions, you need to know how to [pass data from page to page](./pass-data).
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.

You can create your own function to process your data. For example, this function will return the last "count" characters as follows:

```
{{ lastCharacters(data['phone-number'], 4) }}
```

### Create a Nunjucks function

Add your own functions to the `app/functions.js` file. functions are written in JavaScript.

```
const govukPrototypeKit = require('govuk-prototype-kit')
const addfunction = govukPrototypeKit.views.addfunction
addfunction('lastCharacters', function (text, count) {
return text.substring(text.length - count)
})
```

Then use it on a page like this:

```
{{ lastCharacters(data['phone-number'], 4) }}
```

### Use HTML in a Nunjucks function

If you want to use HTML in a function, use the `renderAsHTML` option like this:

```
addfunction('lastCharactersBold', function (text, count) {
return '<strong>' + text.substring(text.length - count) + '</strong>'
}, { renderAsHtml: true })
```

Then use it on a page like this:

```
{{ lastCharactersBold(data['phone-number'], 4) }}
```
3 changes: 3 additions & 0 deletions docs/v13/views/tutorials-and-guides.html
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ <h3 class="govuk-heading-s">Advanced usage</h3>
<li>
<a href="./date-filters">Use filters to add dates</a>
</li>
<li>
<a href="./functions">Use functions to change how answers appear</a>
</li>
<li>
<a href="./examples/override-service-name">Change the service name on one page</a>
</li>
Expand Down

0 comments on commit 85161b6

Please sign in to comment.