如何在SilverStripe中使用模板中的参数调用函数

Lets say I have the following function:

function fruit ($request) {
    ...
    $response = array('apple' => '1dollars', 'mango' => '2dollars');
    return json_encode($response);
}

I want to access something like $response.apple inside my template.

I have tried the following but this does not work as nothing shows on my page:

<% control response %>
    <h1>$response.apple<h2>;
<% end_control %>

If I try to access the function fruit from my template, fruit giving me an error. fruit(request) also gives me an error.

But if I go to fruit which is returning my data absolutely fine:

["apple":"1dollar","mango":"2dollar"]

You need to do two things differently:

  1. You must wrap your data array in an ArrayData or ArrayList object if you want it to be accessible in a template.
  2. You must either return a raw array (in which case the template ControllerName_actionName.ss will be rendered automatically) or explicitly return a rendered template.

So more like:

function fruit ($request) {
    ...
    return $this->customise(array(
        'response' => new ArrayData(array(
            'apple' => '1dollars', 
            'mango' => '2dollars'
        ));
    ))->renderWith(array('YourTemplate'));
}

Note that the naming of "response" is totally arbitrary there. The other possible way to do it is to make "response" a method on your controller (obviously I would name it something different, I'm just keeping your names for clarity):

public function response() {
    return new ArrayData(array(
            'apple' => '1dollars', 
            'mango' => '2dollars'
        ));
}

In which case you can just return the following in your action:

return $this->renderWith(array('MyTemplate'));