-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Documentation for nunjucks functions
- Loading branch information
1 parent
8215589
commit 85161b6
Showing
2 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) }} | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters