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 %> >  
          Image
     </li>
<% 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 (3 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.)

    Appreciated!

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

    Silverstipe now includes numerous methods to help with this sort of thing, including a MultipleOf method:
    http://doc.silverstripe.org/sapphire/en/reference/advanced-templates#modulus-and-multipleof.

    And also see the reference docs for the ViewableData class that has a number of other methods that may be useful:
    http://api.silverstripe.org/2.4/sapphire/view/ViewableData.html

  • Matt Clegg
    03/09/2013 1:15pm (12 months 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.

Advertisement

Site of the Month

Find SSbits on

Top Contributers

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

View full leaderboard


Advertisement