Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending variables to the layout in Zend Framework

The layout is a view, so the method for assigning variables is the same. In your example, if you were to echo $this->whatever in your layout, you should see the same output.

One common problem is how to assign variables that you use on every page to your layout, as you wouldn't want to have to duplicate the code in every controller action. One solution to this is to create a plugin that assigns this data before the layout is rendered. E.g.:

<?php

class My_Layout_Plugin extends Zend_Controller_Plugin_Abstract
{
   public function preDispatch(Zend_Controller_Request_Abstract $request)
   {
      $layout = Zend_Layout::getMvcInstance();
      $view = $layout->getView();

      $view->whatever = 'foo';
   }
}

then register this plugin with the front controller, e.g.

Zend_Controller_Front::getInstance()->registerPlugin(new My_Layout_Plugin());


Without using helpers or plugins do :

Zend_Layout::getMvcInstance()->assign('whatever', 'foo');

After this you can use the following in your layout:

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

This will print "foo".


I have a implemented a Base Controller which all other controllers extend.

So I have a controller...

<?php
class BaseController extends Zend_Controller_Action
{
  public function init()
  {
    $this->view->foo = "bar";
  }
}

and in the layout and/or view

<?= $this->foo ?>

The standard view variables are available if you use the layout within the MVC. In bootstrap file, include this:

Zend_Layout::startMvc();

You must then tell each controller (or even each action, if you wanted granular control over several different layouts) which layout to use. I put mine in the init() of each controller. Here's an example, if your layout file is named layout.phtml:

$this->_helper->layout->setLayout('layout');

Well i guess you can have another solution by creating view helper.. create a file in application/views/helper and name it what ever you want abc.php then put the following code over there.

class Zend_View_helper_abc {

    static public function abc() {
        $html = 'YOUR HTML';
        return $html;
    }
}

So you can use this helper in layout like..

<?= $this->abc() ?>

class IndexController extends Zend_Controller_Action
{

   public function init()
   {
      $this->_layout = $this->_helper->layout->getLayoutInstance();
      $this->_layout->whatever = $this->view->render('test.phtml);
   }
}

In the layout file you can call

<p><?php echo $this->layout()->whatever ?>

If in some actions if you don't want that section then:

public function viewAction()
{
   $this->_layout->whatever = null;
}