Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba, simon_w

Counting a controll loop


Reply


4 Posts   2179 Views

Avatar
vegetav

Community Member, 23 Posts

10 May 2011 at 4:11am

I know this has been discussed alot throughout the Silverstripe community but I can't seem to get it working, maybe I'm just missing something simple!

I basically have the below code, but I wan't to add the class 'last' to every 6th item for CSS purposes.

(ProjectHolder.ss)
<% control Children %>
<div class="project">
<p>info</p>
</div>
<% end_control %>

People seem to be talking about code similar to this....

(ProjectPage.php)
public function IsSixth(){
return ($this->iteratorPos % 6) == 0;
}

But it doesn't work for me... if I do '$iteratorPos' in my .ss file, It prints the iteratorPos, but by trying a simple print_r($this->iteratorPos) in my IsSixth function it returns NULL... so I'm presuming this is the problem.

Avatar
Ben_W

Community Member, 80 Posts

10 May 2011 at 11:37am

Edited: 10/05/2011 11:38am

make sure you put function IsSixth() inside the page class instead of page controller class. Like this.

class ProjectPage extends Page
{
...
public function IsSixth(){
return ((($this->iteratorPos+1) % 6 ) == 0 && $this->iteratorPos!=0);
}
...
}

class ProjectPage_Controller extends Page_Controller
{
//not in here
}

take a note, the $this->iteratorPos start at 0, so if you are after the sixth element you need use ($this->iteratorPos+1). Also I assume you don't want to add the 'last' class to the first element, that's what $this->iteratorPos != 0 is for.

In your template do the following.

<% control Children %>
<div class="project <% if IsSixth %>last<% end_if %>">
<p>info</p>
</div>
<% end_control %>

Avatar
Willr

Forum Moderator, 5513 Posts

10 May 2011 at 5:02pm

If you're using 2.4 you can also use MultipleOf or Modulus directly in the template - http://doc.silverstripe.org/sapphire/en/reference/advanced-templates#modulus-and-multipleof

<% if MultipleOf(6) %>sixth<% end_if %> should work.

Avatar
vegetav

Community Member, 23 Posts

10 May 2011 at 9:11pm

Thanks guys... very helpful... Ben's fix for my IsSixth function works but In the end I when for the <% if MultipleOf(6) %> option, I didn't realise that SilverStripe had that function built in

Cheers!