簡體   English   中英

有沒有更好的方法來使用 twig 測試嵌套數組中存在的值

[英]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 %}

它有效但不是很優雅。 有什么辦法可以改善它嗎?

謝謝

您也可以使用 filter filter來解決這個問題

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

演示


使用not == 0也可以

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

變化不大,但如果您知道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 %}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM