1

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

1
  • Why iterate over attributes if you know the key? Commented Jun 10, 2020 at 11:12

2 Answers 2

2

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 %}

demo


Using not instead == 0 also works

{% if not btns|filter(v => v.attributes['aria-label']|default == 'Close') | length %}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this and the twigfiddle link!
0

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 %}

1 Comment

{% if btn.attributes['aria-label']|default == 'Close' %} would be shorter

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.