diff --git a/CHANGELOG.md b/CHANGELOG.md index e00eea7321..ebd9ed7fd1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/filters/core-filters.js b/lib/filters/core-filters.js index f96df7720c..995cfbf112 100644 --- a/lib/filters/core-filters.js +++ b/lib/filters/core-filters.js @@ -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('')) + + 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('') + ) + + 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 })) + : [] + ) })