Test for empty items in radios and checkboxes
See original GitHub issueI’d like to propose testing if items inside the items
array for checkboxes and radios are empty. If they are, don’t output markup.
My use case
I want to conditionally show a radio based on some data.
In Nunjucks I can alter a value of an item in an array by adding a conditional after it - but it still outputs an empty item and I’ve not worked out how to not provide it.
I could prepare my data in advance - but for a simple thing like this, doing it directly is more readable IMHO. You can see the logic directly.
Example macro:
{{ govukRadios({
idPrefix: "where-do-you-live",
name: "where-do-you-live",
fieldset: {
legend: {
text: "Where do you live?",
isPageHeading: true,
classes: "govuk-fieldset__legend--xl"
}
},
items: [
{
value: "england",
text: "England"
},
{
value: "scotland",
text: "Scotland"
},
{
value: "wales",
text: "Wales"
},
{
value: "northern-ireland",
text: "Northern Ireland"
},
{
divider: "or"
} if data.showFantasy == true,
{
value: "narnia",
text: "Narnia"
} if data.showFantasy == true
]
}) }}
This mostly works - but right now outputs a blank space and random html doing nothing:
Suggested fix
Either strip out empty items from the items
array or else test whether they’re empty when iterating over them.
This feels like a safer thing to do / more defensive. We don’t output markup where there’s no input.
I had a quick test of this by editing the radios macro directly in my node_modules, and it appears to work well.
Issue Analytics
- State:
- Created 4 years ago
- Comments:12 (10 by maintainers)
Top GitHub Comments
I’ve had a go at this and it looks like a sensible suggestion to only output items when they are truthy like Ed has suggested.
Will see what the rest of the team thinks, we’d want to do this for all the components I’ve mentioned above as well.
Ah, sorry @edwardhorsford, my bad. If you can raise a separate issue that’d be great – I don’t believe it’s solved by #1512 (though we do test for
{% if item.conditional %}
, so I’m not entirely sure what’s going on there).