5

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?

Freemium
  • 450
  • 6
  • 16

2 Answers2

5

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

bummzack
  • 5,805
  • 1
  • 26
  • 45
  • Wicked! May I ask where you found out about this? Have never seen it in the docs. Regarding the last bit - I too CSS everything where ever possible but I'm using this to create multiple containers within a single loop and spread data across them; so this isn't something CSS would be ideal for as I'm working with the actual structure of the template, not the style of it. – Freemium May 27 '16 at 15:45
  • 1
    @Freemium Ah I see. I've looked at the API of [`SSViewer_BasicIteratorSupport`](http://api.silverstripe.org/3.3/class-SSViewer_BasicIteratorSupport.html). The more complex approach would have been to add your own `TemplateIteratorProvider` – bummzack May 27 '16 at 15:50
  • 1
    for the later @bummzack mentioned see also http://stackoverflow.com/questions/14096216/pos-from-bottom-inside-loop-dataobjects – munomono May 31 '16 at 19:13
0

Tnks! And it also worked for me...

<% if $FromEnd(0) != 0 %>
    <%-- conditional stuff for all items but the last one in a list --%>
<% end_if %>
Estr3s
  • 1
  • 2