Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add format items filter to core filters #2384

Merged
merged 6 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 }))
: []
)
})