Skip to content

Commit

Permalink
Support name spaced globals
Browse files Browse the repository at this point in the history
  • Loading branch information
BenSurgisonGDS committed Mar 20, 2023
1 parent db824dd commit e88fa25
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const pluginFooViewMarkup = `
{% block content %}
{% include "foo.njk" %}
<div id="test-foo-strong-filter">{{ 'abc' | foo__strong }}</div>
<div id="test-foo-emphasize-function">{{ fooEmphasize('def') }}</div>
<div id="test-foo-emphasize-function">{{ foo.styles.emphasize('def') }}</div>
<div id="test-foo-field-macro">{{ fooField('pass', value='ghi') }}</div>
{% endblock %}
Expand Down
2 changes: 1 addition & 1 deletion cypress/fixtures/plugins/plugin-foo/functions.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
const { addFunction } = require('govuk-prototype-kit').views
addFunction('fooEmphasize', (content) => `<em>${content}</em>`, { renderAsHtml: true })
addFunction('foo.styles.emphasize', (content) => `<em>${content}</em>`, { renderAsHtml: true })
22 changes: 21 additions & 1 deletion lib/functions/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,27 @@ function addGlobalToEnvironment (name, fn, config) {
return new nunjucks.runtime.SafeString(html)
}
}
environment.addGlobal(name, fnToAdd)

if (!name.includes('.')) {
environment.addGlobal(name, fnToAdd)
} else {
const [key, ...rest] = name.split('.')
try {
environment.getGlobal(key)
} catch (err) {
environment.addGlobal(key, {})
}
rest.reduce((obj, next, index) => {
if (index < rest.length - 1) {
if (!obj[next]) {
obj[next] = {}
}
return obj[next]
}
obj[next] = fnToAdd
return null
}, environment.getGlobal(key))
}
}

function addFunction (name, fn, config) {
Expand Down

0 comments on commit e88fa25

Please sign in to comment.