How to pass custom data to a template
Asked Answered
H

1

5

I am new to OOP frameworks in general and Silverstripe in particular. I'm sure I'm missing something vital!

I am currently trying to create a twitter feed for my main page. In my Page_controller I have:

public function getTwitterFeed() { ... }

...which gets a set of tweets. I can format this data any way I like so the structure of the data and the function should be irrelevant.

In the Silverstripe tutorials they give the following example:

public function LatestNews($num=5) {
    $holder = NewsHolder::get()->First();
    return ($holder) ? News::get()->filter('ParentID', $holder->ID)->sort('Created', 'DESC')->limit($num) : false;
}

This is then called in the template as follows:

<% loop LatestNews %>
    <% include NewsTeaser %>
<% end_loop %>

However this function is based on a DataModel object (NewsHolder) and is getting data out of the database (which my twitter function is not).

So what type of variable should this function return? An array? An object?

Halicarnassus answered 22/8, 2012 at 14:18 Comment(3)
You question lacks code. You just posted a function signature and that's it. You are also talking about "this data" -> What data?Putrefaction
@Putrefaction I've added more details.Halicarnassus
@Halicarnassus btw no need to use brackets with the ternary operator... it only makes PHP do more work - "return $holder ? $a : $b;" is the same as "return ($holder) ? $a : $b;" just more cpu cyclesTse
F
16

in SilverStripe 3.0 there are the 2 things called <% loop %> and <% with %>

  • <% loop %> expects anything that implements SS_List (eg: DataList, ArrayList)
  • <% with %> accepts any type of object that extends ViewAbleData I think (eg: DataObject, ArrayData, ...)

(in SilverStripe 2.x there is just <% control %> which does both things)

so, you want to do <% loop TwitterFeed %>? Then you need to return an ArrayList

a short example (not tested, but should work):

    public function getTwitterFeed() {
            return new ArrayList(array(
                    new ArrayData(array(
                            'Name' => 'Zauberfisch',
                            'Message' => 'blubb',
                    )),
                    new ArrayData(array(
                            'Name' => 'Foo',
                            'Message' => 'ohai',
                    )),
                    new ArrayData(array(
                            'Name' => 'Bar',
                            'Message' => 'yay',
                    ))
            ));
    }


    <% loop TwitterFeed %>
            $Name wrote: $Message<br />
    <% end_loop %>

so, just turn your array that you get from twitter into ArrayData objects and put them all into a ArrayList (each tweet should be 1 ArrayData Object)

Factional answered 22/8, 2012 at 15:16 Comment(1)
That's what I was after! Thanks a lot!Halicarnassus

© 2022 - 2024 — McMap. All rights reserved.