Mr_Chimp Mr_Chimp - 5 months ago 26
PHP Question

How to pass custom data to a template

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?


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)