Zend_Layout 快速入门
布局脚本
在两种情况下都需要创建布局脚本。布局脚本简单地使用Zend_View(或者无论哪种你在使用的视图实现)。布局变量用 如下例:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Site</title>
</head>
<body>
<?php
// fetch 'content' key using layout helper:
echo $this->layout()->content;
// fetch 'foo' key using placeholder helper:
echo $this->placeholder('Zend_Layout')->foo;
// fetch layout object and retrieve various keys from it:
$layout = $this->layout();
echo $layout->bar;
echo $layout->baz;
?>
</body>
</html>
因为
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?= $this->headTitle() ?>
<?= $this->headScript() ?>
<?= $this->headStyle() ?>
</head>
<body>
<?= $this->render('header.phtml') ?>
<div id="nav"><?= $this->placeholder('nav') ?></div>
<div id="content"><?= $this->layout()->content ?></div>
<?= $this->render('footer.phtml') ?>
</body>
</html>
和Zend Framework MVC一起使用 Zend_Layout
首先,来看看如何初始化Zend_Layout来和MVC一起使用: <?php // In your bootstrap: Zend_Layout::startMvc(); ?>
在动作控制器例,你可以把局实例作为一个动作助手来访问: <?php
class FooController extends Zend_Controller_Action
{
public function barAction()
{
// disable layouts for this action:
$this->_helper->layout->disableLayout();
}
public function bazAction()
{
// use different layout script with this action:
$this->_helper->layout->setLayout('foobaz');
};
}
?>
在视图脚本里,可以通过
<?php $this->layout()->setLayout('foo'); // set alternate layout ?>
在任何时候,通过 <?php // Returns null if startMvc() has not first been called $layout = Zend_Layout::getMvcInstance(); ?>
最后,
作为例子,让代码首先点击
<body>
<!-- renders /nav/menu -->
<div id="nav"><?= $this->layout()->nav ?></div>
<!-- renders /foo/index + /comment/fetch -->
<div id="content"><?= $this->layout()->content ?></div>
</body>
当和动作堆栈 动作助手 和 插件一起协同使用时,这个特性特别有用,通过循环可以设置一个动作堆栈,这样就创建一个部件化的页面。 使用Zend_Layout做为独立的组件做为独立组件,Zend_Layout不提供和MVC一起使用那样的方便和更多的功能。然而,它仍有两个主要优点:
当用作独立组件,简单地初始化布局对象,使用不同的访问器来设置状态、设置变量为对象属性和解析布局: <?php
$layout = new Zend_Layout();
// Set a layout script path:
$layout->setLayoutPath('/path/to/layouts');
// set some variables:
$layout->content = $content;
$layout->nav = $nav;
// choose a different layout script:
$layout->setLayout('foo');
// render final layout
echo $layout->render();
?>
|