SSbits - Home page
Site by Carbon Crayon
Submit a Post >

Snippets - Little bits of code to make you happy

Manipulating every Nth item in a <% control %> loop

Often you will want to manipulate every nth item inside a <% control %> loop. For example say you had a gallery and you wanted every 3rd image to start on a new line, you need to be able to test each item from the template to see if it is divisible by 3 and should therefore have the clear CSS class added to it.

Using iteratorPos % we can very easily achieve this. First we need to add the test function to the object we will be iterating through, so for example if you are iterating through a number of ImageItem DataObjects, we would add this function to our ImageItem class:

public function IsThird(){	
	return ($this->iteratorPos % 3) == 0;


The % operator calculates the modulous or Remainder after dividing by the number that follows it (in this case 3). If there is a remainder then we know that the item is not divisible by 3 and so should not be cleared, but if the modulous is equal to 0 then we know it is divisible by 3 and should therefore clear a new line.

We can now use <% if IsThird %> to clear the third image in our template <% control %> loop like so:

<% control ImageItems %> 
     <li <% if IsThird %>class="clear"<% end_if %> >  
<% end_control %>
Aram Balakjian avatar

Aram Balakjian

Aram is a web developer running London based agency Aab Web. He has a strong passion for developing attractive, usable sites around the SilverStripe CMS.

  • aleks
    22/02/2011 5:12pm (6 years ago)

    Thanks, I was looking for something basic like this and couldn't find any useful help in the official manual. (Same as nearly always.)


  • Pete Bacon Darwin
    12/05/2011 1:50pm (6 years ago)

    Silverstipe now includes numerous methods to help with this sort of thing, including a MultipleOf method:

    And also see the reference docs for the ViewableData class that has a number of other methods that may be useful:

  • Matt Clegg
    03/09/2013 1:15pm (4 years ago)

    In SS3 this can be called from the template using;

    <% if MultipleOf(3) %>

Post a comment ...

You cannot post comments until you have logged in. Login Here.


Site of the Month

Find SSbits on

Top Contributers

Rank Avatar Name
1 article image Aram Balakjian
2 article image wfacewomens
3 article image Daniel Hensby
4 article image Marcus Dalgren
5 article image ryduhartchas
6 article image Hamish Campbell
7 article image Ty Barho
8 article image Martijn van Nieuwenhoven
9 article image Darren-Lee
10 article image Roman Schmid

View full leaderboard