如何在循环中获取倒数第二个项目
How to get second to last item in loop
Silverstripe 有帮助程序获取循环中的第一个和最后一个项目以及当前项目在循环中的位置/计数。
虽然我找不到倒数第二个项目时如何捕获...
我尝试过一些琐碎的事情(这通常适用于大多数语言),例如
<!-- Right now I know the total is 11, so result should be 10 -->
<!-- Total value will always vary so needs to be dynamically worked out -->
<% if $Pos == $TotalItems-1 %>
$Pos
<% end_if %>
&&
<% if $Last-1 %>
$Pos
<% end_if %>
这行不通,AFAIK 不像 JavaScript 或 PHP 或任何你不能拍 -1 来获得循环/数组中的倒数第二个项目。
我需要做什么才能做到这一点?
您可以使用 $FromEnd
。它将 return 到列表末尾的距离。默认情况下,它以 1
开头,与 $Pos
相同。所以列表中的最后一项是 $FromEnd == 1
。列表中的倒数第二个项目将是 $FromEnd == 2
.
您还可以将起始索引作为参数传递给函数,因此这也会 select 倒数第二个项目:$FromEnd(0) == 1
.
在您的模板中,它看起来像这样:
<% if $FromEnd(0) == 1 %>
<%-- conditional stuff for the second-last item --%>
<% end_if %>
<% if $FromEnd(0) < 2 %>
<%-- conditional stuff for the two last items in a list --%>
<% end_if %>
一般来说,我几乎不用这些方法。如果它与正确格式化项目有关,我建议改用 CSS(例如 nth-child
、nth-last-of-type
等)。
谢谢!它也对我有用...
<% if $FromEnd(0) != 0 %>
<%-- conditional stuff for all items but the last one in a list --%>
<% end_if %>
Silverstripe 有帮助程序获取循环中的第一个和最后一个项目以及当前项目在循环中的位置/计数。
虽然我找不到倒数第二个项目时如何捕获...
我尝试过一些琐碎的事情(这通常适用于大多数语言),例如
<!-- Right now I know the total is 11, so result should be 10 -->
<!-- Total value will always vary so needs to be dynamically worked out -->
<% if $Pos == $TotalItems-1 %>
$Pos
<% end_if %>
&&
<% if $Last-1 %>
$Pos
<% end_if %>
这行不通,AFAIK 不像 JavaScript 或 PHP 或任何你不能拍 -1 来获得循环/数组中的倒数第二个项目。
我需要做什么才能做到这一点?
您可以使用 $FromEnd
。它将 return 到列表末尾的距离。默认情况下,它以 1
开头,与 $Pos
相同。所以列表中的最后一项是 $FromEnd == 1
。列表中的倒数第二个项目将是 $FromEnd == 2
.
您还可以将起始索引作为参数传递给函数,因此这也会 select 倒数第二个项目:$FromEnd(0) == 1
.
在您的模板中,它看起来像这样:
<% if $FromEnd(0) == 1 %>
<%-- conditional stuff for the second-last item --%>
<% end_if %>
<% if $FromEnd(0) < 2 %>
<%-- conditional stuff for the two last items in a list --%>
<% end_if %>
一般来说,我几乎不用这些方法。如果它与正确格式化项目有关,我建议改用 CSS(例如 nth-child
、nth-last-of-type
等)。
谢谢!它也对我有用...
<% if $FromEnd(0) != 0 %>
<%-- conditional stuff for all items but the last one in a list --%>
<% end_if %>