有没有更好的方法来使用树枝测试嵌套数组中存在的值

is there a better way to test value exists in nested array using twig

我有一个模态框,其中包含由使用此数据数组的 twig 渲染的按钮

"buttons" => [
    [
        "title" => "Copy",
        "type" => "button",
        "attributes" => [
            "data-action" => "confirm"
        ],
        "class" => "btn-primary",
    ],
    [
        "title" => "Cancel",
        "type" => "button",
        "attributes" => [
            "aria-label" => "Close"
        ],
        "class" => "btn-light",
    ]
]

如果已经有一个属性为 "aria-labal='Close'" 的按钮,我希望模式不在顶角显示 [x],因此我添加了这组嵌套的 if 语句和 for 循环。

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

它可以工作,但不是很优雅。有什么办法可以改进吗?

谢谢

变化不大,但如果您知道 btn.attributes 中所需的密钥,则只需检查此密钥是否存在及其值:

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

您也可以使用过滤器 filter 来解决这个问题

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

demo


使用 not 代替 == 0 也有效

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