>我使用宏在TWIG中创建了一个递归函数。这个宏应该计算它可以在嵌套数组中找到描述的次数并返回它。
身体可以帮助我解决出了什么问题吗?小提琴可以在以下位置找到:
https://twigfiddle.com/5uskoi
如您所见,结果是 4,而应该是 6。
谢谢你的时间!
问候碧玉
TWIG代码:
{% macro countArray(item) %}
{% import _self as self %}
{% set total = 1 %}
{% for yesItem in item.yes.items %}
{% set total = total + self.countArray(yesItem) %}
{% endfor %}
{% for noItem in item.no.items %}
{% set total = + total + self.countArray(noItem) %}
{% endfor %}
{{ total }}
{% endmacro %}
{% from _self import countArray %}
{% for item in data.items %}
{{ countArray(item) }}
{% endfor %}
使用此数据:
data:
items:
- description: '1'
yes:
items:
- description: '2'
- description: '3'
no:
items:
- description: '4'
yes:
items:
- description: '5'
- description: '6'
找到了这个问题的解决方案。我在宏调用后添加了 |trim。这将修剪所有空格和与数字一起返回的其他内容。
这导致了将它们加在一起的问题。
树枝小提琴已使用此设置进行了更新,以供进一步参考!
问候碧玉