Liquid循环打印重复条目问题:Freshdesk知识库主题分类列表重复渲染
重复输出的核心原因
分类条目的渲染逻辑被放在了内层文件夹循环内部:只要遍历到当前分类下任意一个有文章的文件夹,就会生成一次分类的HTML节点。如果同一个分类下有N个符合条件的文件夹,就会重复输出N次分类条目,和预期不符。
修正方案
先遍历完当前分类下的所有文件夹,确认该分类下至少有1篇有效文章后,再统一渲染分类条目,每个分类仅输出一次。如果需要显示分类的总文章数,还可以在遍历文件夹时累计所有文件夹的文章数。
兼容写法(适配所有Freshdesk版本)
这个写法不需要依赖分类对象的额外内置字段,先通过遍历文件夹判断是否有文章、统计总文章数:
<div class="category-list__items"> {% for category in portal.solution_categories %} {% assign has_valid_folder = false %} {% assign category_total_articles = 0 %} {# 先遍历当前分类下的所有文件夹,提前判断、统计数据 #} {% for folder in category.folders %} {% if folder.articles_count > 0 %} {% assign has_valid_folder = true %} {% assign category_total_articles = category_total_articles | plus: folder.articles_count %} {% endif %} {% endfor %} {# 仅当分类下有有效文章时,才输出一次分类条目 #} {% if has_valid_folder %} <div class="category-list-item"> <a href="{{category.url}}" class="category-list-item__link"> <div class="category-list-item__content"> <h3 class="category-list-item__title">{{category.name}}({{ category_total_articles }})</h3> </div> </a> </div> {% endif %} {% endfor %} </div>
简化写法(若分类对象内置文章统计字段)
如果你的Freshdesk环境中portal.solution_categories直接提供了分类的总文章数字段(通常为category.articles_count,可在你的主题文档中确认字段名),可以直接跳过内层文件夹循环,代码更轻量:
<div class="category-list__items"> {% for category in portal.solution_categories %} {% if category.articles_count > 0 %} <div class="category-list-item"> <a href="{{category.url}}" class="category-list-item__link"> <div class="category-list-item__content"> <h3 class="category-list-item__title">{{category.name}}({{ category.articles_count }})</h3> </div> </a> </div> {% endif %} {% endfor %} </div>
内容的提问来源于stack exchange,提问作者dpnz
相关产品推荐
相关产品推荐

