如何在循环中向第 2、5、8 和 11 项添加 css class

How to add a css class in a loop to the 2nd, 5th, 8th and 11th item

我在 SilverStripe 模板中有一个循环。在循环的第 2、5、8、11 等项目上,我需要添加一个 css class .service-border.

如何使用 SilverStripe 模板语言实现这一点?

<div class="container">
    <% loop $ServiceBlockItems %>
        <% if $First %>
            <div class="row equal-height-columns">
        <% end_if %>

            <%-- Every 2, 5, 8, 11th iteration I need to add a .service-border class --%>
            <div class="col-md-4 service-inner equal-height-column">
                <i class="icon-custom icon-md rounded-x icon-bg-u $IconName"></i>
                <span>$ServiceHeader</span>
                <p>$Summary</p>
            </div>

        <% if $MultipleOf(3) && not $Last %>
        </div><!-- /end row -->
        <div class="row equal-height-columns">
        <% end_if %>
    <% end_loop %>
        </div><!-- /end row -->
</div><!-- /end container -->

我们可以使用 css :nth-child 选择器来定位我们想要的任何元素,而不是在我们的模板中添加 class。

.container .service-inner:nth-child(2),
.container .service-inner:nth-child(5),
.container .service-inner:nth-child(8),
.container .service-inner:nth-child(11) {
    background-color: red;
}

或者如果我们想定位从元素 2 开始的每三个元素,我们可以使用以下 css 选择器:

.container .service-inner:nth-child(3n - 1) {
    background-color: green;
}

nth-child is a css3 selector, which now has very good browser support.

虽然我也更喜欢使用 CSS,但使用 SilverStripe 模板的方法如下:

<% loop $Items %>
    <% if $MultipleOf(3, 2) %>
        <div class="item service-border">
    <% else %>
        <div class="item">
    <% end_if %>
        $Value
    </div>
<% end_loop %>

注意 $MultipleOf 的第二个参数。您可以使用它来设置偏移量。