views:

127

answers:

3

Hello, how could I add some variables to my layout.phtml? I could add it in every Controller like here: http://stackoverflow.com/questions/1537700/sending-variables-to-the-layout-in-zend-framework

But that's not really suggestive and in the Bootstrap I don't want to add it too.

A: 

It sounds like you're trying to keep view content out of the controller. I also believe in trying to keep view content out of the controller, so I try to place view content in my views whenever possible. I do it this way:

For example, in layout.phtml I might have two placeholders, one for the title and another for main content:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title><?php echo $this->escape($this->placeholder('titleContent')) ?></title>
</head>
<body>
  <div id="maincontent">
    <?php echo $this->layout()->content ?>
  </div>
</body>

and then in the index.phtml view itself I put both pieces of content like this:

<?php $this->placeholder('titleContent')->Set('My Index Page Title') ?>
<p>Index page content here</p>

You can add as many placeholders as you want with no impact to your controllers. With this method most content stays out of the controller unless it comes from the model.

Keith Morgan
+1  A: 

Create new abstract controller that will be extending Zend_Controller_Action.

IndexController extends My_Controller_Action -> My_Controller_Action extends Zend_Controller_Action

And there you should put in an init() whatever you want. :)

hsz
Okay, think that this would work, I'll try it =)!
+1  A: 

You could create a front-controller plugin called LayoutDefaults:

class MyLib_Controller_Plugin_LayoutDefaults extends Zend_Controller_Plugin_Abstract
{    
  public function preDispatch(Zend_Controller_Request_Abstract $request)
  {
    $mvc = Zend_Layout::getMvcInstance();
    if ( !$mvc ) return;
    $view = $mvc->getView();
    if ( !$view ) return;

    /**
     * Set the defaults.
     */
    $view->value1 = "default value1";
  }
}

In your Front Controller:

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

In your layout.phtml:

<?= $this->escape($this->value1) ?>

And finally, in your controllers, override the default as needed:

$this->view->value1 = "new value 1";
Derek Illchuk