Automatic installation of the variable in all templates

Notice: This thread is very old.
bafoed
Member | 6
+
0
-

How to load a variable in all the templates?

abstract class BasePresenter extends Nette\Application\UI\Presenter
{
    public function __construct() {
        $this->template->u = $this->session->getSection('user')->user;
    }
}

Throws:

Call to a member function getByType() on a non-object.
File: ...\libs\Nette\Application\UI\Presenter.php   Line: 1433

and

abstract class BasePresenter extends Nette\Application\UI\Presenter
{
    public function __construct() {
        parent::__construct();
        $this->template->u = $this->session->getSection('user')->user;
    }
}

Throws:

Argument 1 passed to Nette\Application\UI\Presenter::__construct() must implement interface Nette\DI\IContainer,
none given, called in \path\to\app\presenters\BasePresenter.php on line 13 and defined
Vojtěch Dobeš
Gold Partner | 1316
+
0
-

You forgot to call parent::__construct(); first. But that's not the ideal solution. Move your code to beforeRender() method.

protected function beforeRender()
{
	parent::beforeRender();
	$this->template->u = $this->session->getSection('user')->user;
}

Presenters will be refactored in close future, but now it's better to avoid using presenter's constructor.

Last edited by vojtech.dobes (2012-03-25 18:49)

bafoed
Member | 6
+
0
-

It helped. Thank you very much.

duke
Member | 650
+
0
-

Btw, the $user variable is passed to presenter templates and presenter components' templates automatically (it is filled with instance of Nette\Security\User).

uestla
Backer | 799
+
0
-

Even better approach to this is to rewrite the createTemplate() method…

protected function createTemplate($class = NULL)
{
	$template = parent::createTemplate($class);
	$template->u = $this->getSession('user')->user;
	return $template;
}