首页 > 解决方案 > 迭代 Shopware Array 并试图让密钥不起作用

问题描述

嘿,我目前正在尝试获取 Shopware 6 中第一个菜单导航的描述。为此,我使用数组 page.header.navigation.active.breadcrumb 并在 page.header.navigation.tree[key].description 中使用其键,但我的键值为空。发生这种情况是因为钥匙无缘无故空了。

这是我的代码:

{% sw_extends "@Storefront/storefront/section/cms-section-sidebar.html.twig" %}

{% set topMenu = null %}
{% for key, value in page.header.navigation.active.breadcrumb %}
    {% if loop.index == 2 %}
        {% set topMenu = value %}
        {# {% set topMenuDescription = page.header.navigation.tree[key].category.description %} #}
        {% set topMenuDescription = key %}
    {% endif %}
{% endfor %}
{% set currentMenu = page.header.navigation.active.breadcrumb | last %}
{# {% set currentMenu = page.header.navigation.active.name %} #}
{# {% set topMenuDescription = page.header.navigation.active.description %} #}
{# {% if ! topMenuDescription %}
    {% set topMenuDescription = page.header.navigation.active.description %}
{% endif %} #}

{% block section_main_content_block %}
    <div class="category-top">
        <div class="category-banner">
            <img src="/media/6a/fd/8b/1632946677/listing-banner.jpg">
            <div class="category-banner-headlines">
                {% if (currentMenu != topMenu) %}
                    <h3>{{ topMenu }}<h3>
                    <h2>{{ currentMenu }}<h2>
                {% else %}
                    <h2 class="sameMenu">{{ currentMenu }}<h2>
                {% endif %}
            </div>
        </div>
        <div class="category-description">
            <h1>{{ currentMenu }}</h1>
            {{ topMenuDescription | trans | raw }}
        </div>
    </div>
    {{ parent() }}
{% endblock %}

这里也是我想要获取的密钥的结构: key-i-want-to-get

这是我想要得到的描述: description-i-want-to-get

旁注:我的示例中的描述是空的,因为我在单独的测试区域进行展示,我没有设置描述

标签: twigshopware

解决方案


原因topMenuDescription是空的,因为变量只存在于{% for %}您创建的 -loop 的范围内。在此循环之外,该变量不存在。

为了解决这个问题,您需要通过在-looptopMenuDescription之外定义变量来更改范围{% for %}

{% set topMenuDescription = null %}
{% for key, value in page.header.navigation.active.breadcrumb %}
    {% if loop.index == 2 %}
        {% set topMenu = value %}
        {# {% set topMenuDescription = page.header.navigation.tree[key].category.description %} #}
        {% set topMenuDescription = key %}
    {% endif %}
{% endfor %}

边注

您确实应该在开发时启用 twig 的调试,因为您当前的代码段会抛出一个RuntimeError解释变量不存在的信息。


推荐阅读