views:

1249

answers:

3

Hi

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?

+5  A: 

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());

Tim Fountain
cool thanks... I have another solution I'll post now for other peoples reference
sfusion
where do I put this plugin (which folder?) and where do I set `Zend_Controller_Front::getInstance()->registerPlugin(new My_Layout_Plugin());`?
Rodrigo Alves
That line will work anywhere, but the usual place to do this is in your Bootstrap class
Tim Fountain
A: 

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 ?>
sfusion
Does that work? is there a hidden question in that :)
Andi
While I like this idea, I can't help but think a view helper would have been a better idea.
azz0r
Base controller is almost always a very BAD idea. Controller plugins and controller helpers were created specifically to address the base controller inflexibility (which can be summarized as composition over inheritance). So, unless you know all the implications - never rely on custom base controller.
Victor Farazdagi
+2  A: 

Without using helpers or plugins do :

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

then in your layout :

$this->layout()->whatever;

will print foo in your layout file.

10us
For simple assignments, this is a perfectly elegant solution! Love it. 1+
Zenph