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