首页 > 解决方案 > 每次迭代树枝循环时减去一个

问题描述

我必须在 twig 中制作一个评级星列表,但我不知道如何在每次迭代循环时减去一颗星,以便它在列表中少显示一颗星。

我有以下代码:

<ul>
    {% for input in 0..3 %}
        <li>
            <input type="radio" name="stars" />
            <label>
                {% for i in 0..4 %}
                    <span></span>
                {% endfor %}
                {% if input >= 1 %} <span class="stars">and more</span>{% endif %}
            </label>
        </li>
    {% endfor %}
</ul>

星星是用 CSS 制作的,所以我需要第二个循环在每次迭代时少显示一颗星星。

标签: phpcsstwig

解决方案


您需要在for-loops 中使用一个变量来跟踪最大数量的星星。

<ul>
    {% set j = 5 %}{# max amount of stars #}
    {% for input in 1..j %}{# this will be 5 all the time, because it's allready interpreted #}
        <li>
            <input type="radio" name="stars" />
            <label>
                {% for i in 1..j %}
                    <span></span>
                {% endfor %}
                {% if input >= 1 %} <span class="stars">y más</span>{% endif %}
            </label>
        </li>
        {% set j = j - 1 %}{# lower the amount of stars that will be shown next iteration #}
    {% endfor %}
</ul>

演示


推荐阅读