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

查看:18
本文介绍了将变量发送到 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->whatever,您应该看到相同的输出.

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天全站免登陆