Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get second to last item in loop

Tags:

silverstripe

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?

like image 676
Freemium Avatar asked May 27 '16 14:05

Freemium


People also ask

How to get the 2nd to the last value of an array?

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.

How do you loop through a list from the last element in Python?

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.

How to access last array element in JavaScript?

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.


1 Answers

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.).

like image 88
bummzack Avatar answered Oct 22 '22 10:10

bummzack