Jump to:

23371 Posts in 18161 Topics by 2865 members

General Questions

SilverStripe Forums » General Questions » Counting elements in a template

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

Page: 1
Go to End
Author Topic: 1625 Views
  • pipworks
    Avatar
    Community Member
    10 Posts

    Counting elements in a template Link to this post

    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.

  • pipworks
    Avatar
    Community Member
    10 Posts

    Re: Counting elements in a template Link to this post

    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 %>

    1625 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.