Sending variables to the layout in Zend Framework

Viewed 41338

In my project I have a number of dynamic elements that are consistently on every page. I have put these in my layout.phtml

My question is: How can I send variables into my layout from my controllers?

If I want to send things from my controller I can use:

$this->view->whatever = "foo";

And receive it in the view with

echo $this->whatever;

I cannot figure out how to do the same with my layout. Perhaps there is a better way around the problem?

8 Answers

As a side note, if you send json at some point in your app be careful that global view variables are not sent with the response.

View Helpers are also a good idea. I had a ecommerce website, which I had a layout.phtml with menus with categories and subcategories that I needed to bring from the database.

For this, I did the following:

Bootstrap.php:

protected function _initHelperPath() 
{

    $view = $this->bootstrap('view')->getResource('view');

    $view->setHelperPath(APPLICATION_PATH . '/views/helpers', 'View_Helper');

}

application.ini:

resources.view[]=

In views/helpers, I had a file called Menus:

class View_Helper_Menus extends Zend_View_Helper_Abstract {

    public function categories(){

       $categories = new Application_Model_DbTable_Categories();

       return $categories->fetchAll();

    }

    public function subCategories(){

        $subCategories = new Application_Model_DbTable_SubCategories();

        return $subCategories->fetchAll();

    }

}

In layout.phtml, I just had to call the specific helper, and call the methods from it:

$menu = $this->getHelper('Menus');
$categories = $menu->categories();
$subCategories = $menu->subCategories();

Hope it helps someone that needs to bring data from database to render the layout.

Related