递归调用HTML模板时maxCategories计数器值异常排查
递归遍历分类时计数器无法正确累计的问题修复
问题现象
递归调用HTML模板遍历带特定自定义字段的分类时,控制展示数量的maxCategories计数器出现异常,表现为:1(分类)、2(分类)、2(子分类)、3(子分类)、4(最后一个子分类)、2(分类)、3(分类)。
- 仅保留父分类时,仍出现1、2、2...的异常计数
- 将代码拆分为多个
for+if语句及独立模板可正常运行,但希望修复递归方案的问题
问题原因
Twig中变量是按值传递的,递归调用category_links宏时,传递的是maxCategories的当前值副本,子递归中对计数器的修改不会同步回父级。同时,父循环中若某个分类不满足自定义字段条件,后续分类的计数器会基于未更新的值继续累加,导致计数重复。
修复方案
修改宏的逻辑,让宏返回更新后的计数器值,确保递归过程中计数状态能正确传递:
{% block homepage_category_lister %} {% macro category_links(navigationTree, maxCategories = 0) %} {% set currentCount = maxCategories %} {% for treeItem in navigationTree %} {% if currentCount < 6 %} {% set category = treeItem.category %} {% set name = treeItem.category.translated.name %} {% if treeItem.category.customFields['custom__test'] == 'yes' %} {% block home_categories_listing_box %} <div class="category--box"> <a href="{{category_url(category)}}" itemprop="url" title="{{ name | striptags }}"> {% sw_thumbnails 'home--categories--teaser--images' with { media: category.media, sizes: { 'default': '4500px' }, attributes: { 'class': 'home--categories--teaser--images', 'alt': (category.media.translated.alt ?: ''), 'title': (category.media.translated.title ?: ''), 'data-object-fit': 'cover', 'loading': 'lazy' } } %} <span itemprop="name" class="category--box--name"> {{ name | striptags }} </span> </a> </div> {% endblock %} {% set currentCount = currentCount + 1 %} {% endif %} {% block home_categories_listing_box_recrussive %} {% if treeItem.children != null %} {% set currentCount = _self.category_links(treeItem.children, currentCount) %} {% endif %} {% endblock %} {% endif %} {% endfor %} {{ currentCount }} {% endmacro %} {% endblock %}
关键修改点
- 新增
currentCount变量承载当前计数,避免直接修改传入的参数 - 递归调用时接收返回的更新后计数,同步到
currentCount - 宏末尾返回最终的
currentCount,让父级递归或调用者获取最新状态
修改后,计数器会在整个递归遍历过程中持续累加,不会出现分支间的计数回退或重复。
内容的提问来源于stack exchange,提问作者Shad0w
相关产品推荐
相关产品推荐

