Zend Framework:如何将默认布局脚本更改为layout.phtml以外的其他内容?

时间:2012-02-03 23:39:51

标签: php zend-framework

我想将我的默认布局文件命名为layout.phtml之外的其他内容,因为它并没有真正描述它的布局类型。我怎样才能做到这一点?谢谢!

2 个答案:

答案 0 :(得分:6)

从您的Bootstrap.php文件中,您可以执行以下操作:

protected function _initLayoutName()
{
    // use sitelayout.phtml as the main layout file
    Zend_Layout::getMvcInstance()->setLayout('sitelayout');
}

如果要为不同的模块使用不同的布局,则需要在Bootstrap中注册插件并使插件包含以下代码:

class Application_Plugin_LayoutSwitcher extends Zend_Controller_Plugin_Abstract
{
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $module = $request->getModuleName(); // get the name of the current module

        if ('admin' == $module) {
            // set the layout to admin.phtml if we are in admin module
            Zend_Layout::getMvcInstance()->setLayout('admin');
        } else if ('somethingelse' == $module) {
            Zend_Layout::getMvcInstance()->setLayout('somethingelse');
        }
    }
}

在application.ini中,您可以执行此操作来设置布局脚本:

resources.layout.layout = "layoutname"

然而,这不适用于每个布局。如果需要根据模块更改布局,则必须使用插件,但可以使用application.ini中的设置来设置默认布局名称。

答案 1 :(得分:3)

如果您希望根据模块具有特定的布局 你可以创建一个插件并在你的boostrap中注册它:

<?php

class Plugin_LayoutModule extends Zend_Controller_Plugin_Abstract 
{
        /**
         * preDispatch function.
         * 
         * Define layout path based on what module is being used.
         */
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
                $module = strtolower($request->getModuleName());
                $layout = Zend_Layout::getMvcInstance();

                if ($layout->getMvcEnabled())
                {
                        $layout->setLayoutPath(APPLICATION_PATH . '/modules/' . $module . '/layouts/');
                        $layout->setLayout($module);
                }
        }
}

//Register it in your bootstrap.php     
    <?php
        defined('APPLICATION_PATH')
            or define('APPLICATION_PATH', dirname(__FILE__));
        ...

        Zend_Layout::startMvc();
        $frontController->registerPlugin(new Plugin_LayoutModule()); 
    ?>

编辑:

使用.ini文件将布局设置为另一个文件:

创建layout.ini文件并输入:

[layout]
layout = "foo"
layoutPath = "/path/to/layouts"
contentKey = "CONTENT"

在你的bootstrap文件中:

$config = new Zend_Config_Ini('/path/to/layout.ini', 'layout');

$layout = Zend_Layout::startMvc($config);