twig - 迭代 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
旁注:我的示例中的描述是空的,因为我在单独的测试区域进行展示,我没有设置描述
解决方案
原因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
解释变量不存在的信息。
推荐阅读
- javascript - Nuxt.js 嵌套路由加载问题
- excel - 禁止excel在公式中生成文件路径
- laravel - Laravel aws s3 存储桶 - 错误执行“PutObject”时出错
- java - JsonPath(放心):从 JsonPath 中获取 JsonPath
- java - 如果语句为真,我想在 ArrayList 中添加元素,但 ArrayList 中对应索引的预期元素发生变化
- c++ - 全局命名空间友元类不能访问命名命名空间类的私有成员
- firebase - 如何在 Windows 防火墙中阻止来自 Firebase 的入站消息
- nestjs - NestJS和问SDK服务注入
- node.js - PuppeteerCrawler 缓存已抓取的请求(抓取器看到的 url)
- swiftui - 捆绑
绑定 在斯威夫特