Skip to content

Commit

Permalink
Merge pull request #2384 from alphagov/allow-users-to-simplify-items
Browse files Browse the repository at this point in the history
Add format items filter to core filters
  • Loading branch information
BenSurgisonGDS authored Dec 1, 2023
2 parents 667abeb + 18f545a commit e306f02
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### New features

- [#2384: Add format items filter to core filters](https://github.com/alphagov/govuk-prototype-kit/pull/2384)
- [#2382: Make any npm module a plugin via a proxy plugin config](https://github.com/alphagov/govuk-prototype-kit/pull/2382)

## 13.15.3
Expand Down
53 changes: 45 additions & 8 deletions lib/filters/core-filters.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,51 @@
const { runWhenEnvIsAvailable, external } = require('./api')
const { addFilter, getFilter } = external

/**
* Logs an object in the template to the console in the browser.
* @param {Any} a any type
* @return {String} a script tag with a console.log call.
* @example {{ "hello world" | log }}
* @example {{ "hello world" | log | safe }} [for environments with autoescaping turned on]
*/
runWhenEnvIsAvailable(() => {
const nunjucksSafe = getFilter('safe')
addFilter('log', a => nunjucksSafe('<script>console.log(' + JSON.stringify(a, null, '\t') + ');</script>'))

addFilter(
'log',
/**
* Logs an object in the template to the console in the browser.
*
* @example
* ```njk
* {{ "hello world" | log }}
* ```
* @param {any} a - any type
* @returns {string} a script tag with a console.log call.
*/
(a) => nunjucksSafe('<script>console.log(' + JSON.stringify(a, null, '\t') + ');</script>')
)

addFilter(
'formatItems',
/**
* Returns an array of objects for use in a macro that requires a list of items
*
* @example
* ```njk
* {{ govukCheckboxes({
* name: "waste",
* fieldset: {
* legend: {
* text: "Which types of waste do you transport?",
* isPageHeading: true,
* classes: "govuk-fieldset__legend--l"
* }
* },
* hint: {
* text: "Select all that apply."
* },
* items: ["Rubble", "Oil", "Card"] | formatItems
* }) }}
* ```
* @param {string[]} items - an array of strings.
* @returns {{ text: string, value: string }[]} an array of objects with text and value properties.
*/
(items = []) => Array.isArray(items)
? items.map((item) => ({ text: item, value: item }))
: []
)
})

0 comments on commit e306f02

Please sign in to comment.