user199337
user199337

Reputation: 8223

Zend Framework: Layout

how could I add some variables to my layout.phtml? I could add it in every Controller like here: 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.

Upvotes: 0

Views: 443

Answers (3)

Derek Illchuk
Derek Illchuk

Reputation: 5658

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";

Upvotes: 1

hsz
hsz

Reputation: 152216

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. :)

Upvotes: 1

keithm
keithm

Reputation: 2813

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">
<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.

Upvotes: 0

Related Questions