|
| 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 | +``` |
0 commit comments