Silverstripe has helpers for getting the first and last items in a loop as well as the position / count of the current item in the loop.
Though I can't find how to capture when it's the second to last item...
I've tried trivial things (that'd usually work in most languages) such as
<!-- 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 %>
This doesn't work, AFAIK unlike JavaScript or PHP or whatever you can't slap a -1 to get the second to last item in a loop / array.
What would I need to do to accomplish this?
To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
The first and last elements are accessed using an index and the first value is accessed using index 0 and the last element can be accessed through length property which has one more value than the highest array index. The array length property in JavaScript is used to set or return the number of elements in an array.
You can use $FromEnd
for that. It will return the distance to the end of a list. By default, this starts with 1
, the same way as $Pos
does. So the last item in a list is $FromEnd == 1
. The second last item in a list would be $FromEnd == 2
.
You can also pass the start index as a parameter to the function, so this would also select the second last item: $FromEnd(0) == 1
.
In your template, this would look like this:
<% 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 %>
Generally, I almost never use these methods. If it's related to properly format items, I advice to use CSS instead (eg. nth-child
, nth-last-of-type
etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With