将变量发送到Zend Framework中的布局 [英] Sending variables to the layout in Zend Framework

查看:93
本文介绍了将变量发送到Zend Framework中的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我有很多动态元素,它们在每个页面上都一致.我已经将它们放在我的layout.phtml

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

并使用

echo $this->whatever;

我无法弄清楚如何对我的布局执行同样的操作.也许有解决这个问题的更好方法?

I cannot figure out how to do the same with my layout. Perhaps there is a better way around the problem?

推荐答案

布局视图,因此分配变量的方法相同.在您的示例中,如果回显$ this->布局中的任何内容,您应该会看到相同的输出.

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

这篇关于将变量发送到Zend Framework中的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆