如何根据 TWIG 中的子值操作计数?
How to manipulate count based on sub-values in TWIG?
我想知道如何根据子规则操作/呈现计数。
目前的情况是统计规格,当规格超过5个时,显示一个link表示更多的规格。我只想显示具有如下值的规格:
{% for spec in product.specs | limit(5) %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% endif %}
{% endfor %}
{% if product.specs | length > 5 %}
<li class="more"><a href="./">{{ 'View all specifications' | t }}</a></li>
{% endif %}
在这种情况下,计数是在检查子项的值之前完成的,因此“显示更多”link 是可见且可点击的,但不会显示更多规格,因为它们已被删除out,因为该值为空但被计为项目。
目标是在小于 5 个具有值的项目时隐藏“显示更多”link。
我希望有人能给我指出正确的方向:-)
非常感谢您和我一起思考!
您可以使用额外的计数器来计算有效元素,
{% for spec in product.specs | limit(5) %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% endif %}
{% endfor %}
{% set cnt = 0 %}
{% for spec in product.specs %}
{% if spec.value %}{% set cnt = cnt + 1 %}{% endif %}
{% endfor %}
{% if cnt >= 5 %}
<li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}
或者您可以使用过滤器 filter
{% if products.specs| filter(spec => spec.value|default) | length >= 5 %}
<li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}
更新您的评论(因为您无权访问 filter
)
你不能只是事先限制结果。所以在第一部分你还需要使用一个计数器
{% set cnt = 0 %}
{% for spec in product.specs %}
{% if cnt < 5 %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% set cnt = cnt + 1 %}
{% endif %}
{% endif %}
{% endfor %}
我想知道如何根据子规则操作/呈现计数。 目前的情况是统计规格,当规格超过5个时,显示一个link表示更多的规格。我只想显示具有如下值的规格:
{% for spec in product.specs | limit(5) %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% endif %}
{% endfor %}
{% if product.specs | length > 5 %}
<li class="more"><a href="./">{{ 'View all specifications' | t }}</a></li>
{% endif %}
在这种情况下,计数是在检查子项的值之前完成的,因此“显示更多”link 是可见且可点击的,但不会显示更多规格,因为它们已被删除out,因为该值为空但被计为项目。
目标是在小于 5 个具有值的项目时隐藏“显示更多”link。
我希望有人能给我指出正确的方向:-)
非常感谢您和我一起思考!
您可以使用额外的计数器来计算有效元素,
{% for spec in product.specs | limit(5) %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% endif %}
{% endfor %}
{% set cnt = 0 %}
{% for spec in product.specs %}
{% if spec.value %}{% set cnt = cnt + 1 %}{% endif %}
{% endfor %}
{% if cnt >= 5 %}
<li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}
或者您可以使用过滤器 filter
{% if products.specs| filter(spec => spec.value|default) | length >= 5 %}
<li class="more"><a href="./">{{ 'View all specifications' }}</a></li>
{% endif %}
更新您的评论(因为您无权访问 filter
)
你不能只是事先限制结果。所以在第一部分你还需要使用一个计数器
{% set cnt = 0 %}
{% for spec in product.specs %}
{% if cnt < 5 %}
{% if spec.value %}
<li>
<span>{{ spec.title }}</span>
{{ spec.value }}
</li>
{% set cnt = cnt + 1 %}
{% endif %}
{% endif %}
{% endfor %}