php - Twig 循环。控制类名

标签 php html css twig

我尝试在 Twig 中根据渲染的元素数量设置不同的类。例如,如果只有一个,如果只有两个,如果只有三个等等,我想在

  • 项上设置不同的类。我该怎么做?

    <ul>
        {% for item in items %}
            <li>
                {% include 'components/list/person.twig' with item %}
            </li>       
        {% endfor %}
    </ul>
    
  • 最佳答案

    如果你想知道循环的长度,可以使用预定义的 loop variable这就是所谓的长度:

    loop.length: The number of items in the sequence

    例如:

    {% for user in users %}
        {{ loop.index }}/{{ loop.length }} - {{ user.username }}
    {% endfor %}
    

    希望这有帮助

    关于php - Twig 循环。控制类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42487121/

    相关文章:

    PHP MYSQL 消除表中的逗号

    php - 困惑为什么mysqli_query返回false

    html - 当父级小于子级时,将 div 在其父级中水平居中

    html - 更改 $mdDialog 的 Angular Material

    html - CSS 和 HTML 在图像上放置偏移内容以产生交错效果

    html - 两个div的高度基于主div的高度相等

    php - jQuery keyup 函数在尝试插入数据库时​​停止工作

    php - Laravel 5 PHP DOM文档

    javascript - 如何从 jquery 更改类但从另一个对象中删除该类

    html - 使用 css 动画在循环中无缝移动箭头