Reputation: 87
I have a modal that has buttons rendered by twig using this data array
"buttons" => [
[
"title" => "Copy",
"type" => "button",
"attributes" => [
"data-action" => "confirm"
],
"class" => "btn-primary",
],
[
"title" => "Cancel",
"type" => "button",
"attributes" => [
"aria-label" => "Close"
],
"class" => "btn-light",
]
]
I want the modal to not show a [x] in the top corner, if there is already a button with the attribute "aria-labal='Close'", so I added this nested set of if statements and for loops.
{% set hideBtnClear = false %}
{% for btn in modal.buttons %}
{% if btn.attributes %}
{% for key, value in btn.attributes %}
{% if key == "aria-label" and value == "Close" %}
{% set hideBtnClear = true %}
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% if hideBtnClear == false %}
[x] <--
{% endif %}
It works but isn't very elegant. Is there any way I can improve it?
Thanks
Upvotes: 1
Views: 409
Reputation: 15643
You could also use the filter filter
to solve this as well
{% if btns|filter(v => v.attributes['aria-label']|default == 'Close') | length == 0 %}
[ X ]
{% endif %}
Using not
instead == 0
also works
{% if not btns|filter(v => v.attributes['aria-label']|default == 'Close') | length %}
Upvotes: 2
Reputation: 54841
Not much of a change, but if you know the required key in btn.attributes
, then just check this key presence and it's value:
{% set hideBtnClear = false %}
{% for btn in modal.buttons %}
{% if btn.attributes['aria-label'] is defined and btn.attributes['aria-label'] == "Close" %}
{% set hideBtnClear = true %}
{% endif %}
{% endfor %}
{% if hideBtnClear == false %}
[x] <--
{% endif %}
Upvotes: 0