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 elements in a template


Reply

2 Posts   1671 Views

Avatar
pipworks

7 June 2010 at 10:22pm Community Member, 10 Posts

Hi, does anyone know how to count the elements in a template page?

I have used the "control children" before, and I can use the $Pos variable on that, but I have a page that lists all grand-children, so if I render $Pos to the elements, it resets each time if starts a new loop of the parent.

All I really want is to count the elements as they are rendered to the template and increment each time.

So it would look something like:

<ul>
<% control GrandChildren %>
<li>$counter</li>
<% end_control %>
</ul>

which would output 1,2,3,4 etc. rather than 1,2,1,1,2,3,1 as $Pos does.

Any help would be very much appreciated thanks.

Avatar
pipworks

8 June 2010 at 12:45am (Last edited: 8 June 2010 5:15am), Community Member, 10 Posts

Ok, just a quick update on this, I've got round this by creating a method for that particular pages controller and looping through its children, then looping through the children of those, then loading each result into an array and returning that array as a new DataObjectSet.

Once I did that, I could use the built in $Pos variable, so I can now use css on any uniquely named element.

function GrandChildren() {
$articleArray = array();
foreach ($this->ChildrenOf($this->ID) as $section) {
foreach($this->ChildrenOf($section->ID) as $article) {
$articleArray[] = $article;
}
}
return new DataObjectSet($articleArray);
}

Then the template just calls the method:

<ul>
<% control GrandChildren %>
<li>
<a href="$Link" class="section$Pos">$Title - $Pos</a>
</li>
<% end_control %>