Passing variables to layout after bootstrapping layout resource

446 views Asked by At

I had to create method in Boostrap which bootstraps Layout resource and registers some view helpers.

protected function _initViewHelpers() {
    $this->bootstrap('layout');
    $layout = $this->getResource('layout');
    $view = $layout->getView();

    $view->registerHelper(new Application_View_Helper_LoadMenu, 'loadMenu');
    $view->registerHelper(new Application_View_Helper_InfoLink, 'infoLink');
    $view->registerHelper(new Application_View_Helper_InfoData, 'infoData');
}

Now, I am passing some variables to layout (to Zend_View instance, as always), but layout doesn't recognize that it has them.

When I move code which registers helpers, to init() method in controller, everything is ok. Is it ZF error or I did sth wrong?

2

There are 2 answers

0
Francis Yaconiello On BEST ANSWER

In Your Controller (or wherever you have view)

$view->layout()->some_var = "Some Value";

In Your Layout

<?php echo $this->layout()->some_var; ?>

if i'm missing some part of your question let me know.

Edit: failing the above, the other correct way to do this would be to use the placeholder helper (http://framework.zend.com/manual/en/zend.view.helpers.html#zend.view.helpers.initial.placeholder)

Edit 2: Make sure you are bootstrapping view as well.

$this->bootstrap('view');
$view = $this->getResource('view');
0
David Weinraub On

Do your view-helpers implement the setView() method, either directly or perhaps as subclasses of Zend_View_Helper_Abstract?

If you look at the code for Zend_View_Abstract::registerHelper($helper, $name) method, you will see that it checks for the presence of a setView() method on the helper. If it finds such a method, then it calls $helper->setView($this), where $this is the $view.

This is where the connection takes place. In the absence of this call, it seems that although the view will be aware of the helper (after all, you did just register it), the helper will be unaware of the view. If the helper tries to access the view, it ends up creating a new view object, which is not the one you configured way back in Bootstrap.

tl;dr: There is probably no need to explicitly register the helpers. With the default resource-autoloader in place and the class/method naming convention you seem to be using, you can probably allow the built-in plugin-loader to handle all the instantiation. Simply call $this->myHelperMethod() in your layouts or view-scripts and all should be cool.