3

I would like to pass some data from my Controller_Template to my template.php.

Here's my controller:

class Controller_User extends Controller_Template {

    public $template = 'template';

    public function action_index() {

        $user = "Alice";

        $view = View::factory('user/user')
            ->bind('user', $user);

        $this->template->content = $view;
    }
}

Doing this means I can access $user in user/user.php, and whatever markup I have in user/user.php is available in $content.

However, I want to access $user in template.php. If I change the bind() method to bind_global('user', $user) then I can indeed access $user in template.php.

The problem though, is that if I do that, there seems to be nothing in $content. Where am I going wrong?

4

1 回答 1

2

The $view (or the $content template variable) ends up being empty when you use bind_global() method for one good reason — it is a static method which doesn't return anything, and since it's the last method called in the $view definition the $view variable ends up being equal NULL.

It is a bit unfortunate (if you ask me) that PHP allows using static methods in an object context, while at the same time it doesn't allow that with properties. And it is this inconsistency (among many others) that causes your problem here.

The way to achieve what you're after would be to bind the $user variable globally in via calling the bind_global() method statically. Full working example:

class Controller_User extends Controller_Template {

    public $template = 'template';

    public function action_index()
    {
        $user = "Alice";
        View::bind_global('user', $user);

        $view = View::factory('user/user');
        $this->template->content = $view;
    }
}

And this should work for you like a charm.

于 2013-03-30T21:56:31.693 回答