【问题标题】:Thymeleaf iterate list with alternate colorsThymeleaf 使用交替颜色迭代列表
【发布时间】:2020-11-10 03:30:14
【问题描述】:

在我的 Spring Boot 项目中,我正在迭代一个 Thymeleaf 列表,如下所示:

<div th:each="filename: ${files}">
<div class="bold badge badge-primary" th:text="${filename}"></div>
</div>

问题:我不知道如何在遍历它们时将徽章主要和徽章次要 (bootstrap4.5) 类分配给备用列表项?

简单来说,第一个列表项应该有 badge-primary 类,第二个列表项应该有 badge-secondary 类。

有可能吗?如果是,那么如何?谢谢。

【问题讨论】:

    标签: spring spring-boot bootstrap-4 thymeleaf


    【解决方案1】:

    当使用th:each 时,Thymeleaf 提供了一种对keeping track of the status of your iteration 有用的机制:状态变量。根据 Thymeleaf 文档示例,您的代码可能如下所示...

    <div th:each="filename,iterStat: ${files}">
        <div class="bold badge badge-primary" th:class="'bold badge'" th:classappend="${iterStat.odd}? 'badge-primary' : 'badge-secondary'" th:text="${filename}"></div>
    </div>
    

    【讨论】:

    • 我喜欢使用th:classappend。我以前没见过。
    • 谢谢,@andrewjames。我发现当您需要使用完整的类列表(Thymeleaf th:class)保留正确的静态视图时,它非常有用,仅使用 th:classappend 的类的基本列表和动态部分。
    • 您可以将其表示为th:class="|bold badge badge-${iterStat.odd ? 'primary' : 'secondary'}|",如果您愿意,可以删除其他所有内容。
    • 太棒了。你真棒。 !正是我想要的。万分感谢。 !
    • @Metroids 这是一款非常酷的单线。感谢分享!
    猜你喜欢
    • 1970-01-01
    • 2015-12-12
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2011-01-27
    • 2014-08-06
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多