Sending variables to the layout in Zend Framework

2020-01-25 05:57发布

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条回答
Summer. ? 凉城
2楼-- · 2020-01-25 06:29

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() ?>
查看更多
Melony?
3楼-- · 2020-01-25 06:33

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

查看更多
登录 后发表回答