Snippets - Little bits of code to make you happy
Manipulating every Nth item in a <% control %> loop
Tweet16 July 2009 | | | Supports v2.4, v2.3
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 %>
2 Comments
RSS feed for comments on this page RSS feed for all comments
aleks
22/02/2011 5:12pm (2 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 (2 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
Post a comment ...
You cannot post comments until you have logged in. Login Here.