Zend Framework 1.x中Zend_Layout使用(实现视图布局)
通用的HTML 代码:Layouts
很明显在views 文件中会有很多通用的HTML 代码,比如页面上重复的header 部分和footer部分,甚至sidebar边栏等。这是一个很常见的问题,Zend 框架使用 Zend_Layout 解决这个问题。Zend_Layout 可以允许我们将通用的header、footer和其他代码移动到布局视图文件代码中,这个布局视图代码中包含为要执行的action指定的view 代码。
第一步:在application.ini中配置layout路径,[production]下加入:
resources.layout.layoutPath = APPLICATION_PATH "/views/scripts/layouts"
resources.layout.layout = "layout"
文件结构如下:

第二步:建立相关文件
layout.phtml文件:
1 <!--www.phpddt.com--> 2 <?php echo $this->render('header.phtml');?> 3 <!--来一个布局变量--> 4 <?php echo $this->layout()->nav ?> 5 <!--默认的,$content 变量被应用程序的视图脚本呈现内容填充。--> 6 <?php echo $this->layout()->content;?> 7 <?php echo $this->render('footer.phtml');?>
header.phtml文件:
1 <html> 2 <head> 3 <title>这是www.phpddt.com</title> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 </head> 6 <body>
nav.phtml文件:
1 <div id="nav" style="margin:20px 0;background-color: red;"> 2 这是导航 3 </div>
footer.phtml文件:
1 <div id="footer" style="background-color: #EEEEEE; height: 30px;"> 2 这是footer 3 </div> 4 </body> 5 </html>
第三步:在动作控制器中:
1 <?php 2 //@blog<http://www.phpddt.com> 3 require_once APPLICATION_PATH.'/models/Article.php'; 4 require_once 'BaseController.php'; 5 require_once 'Zend/Layout.php'; 6 class IndexController extends BaseController 7 { 8 public function init() 9 { 10 parent::init(); 11 //set layout 12 $layout = new Zend_Layout(); 13 $layout->nav = $this->view->render('layouts/nav.phtml'); 14 $layout->setLayout('layout'); 15 } 16 //这里的内容到$this->layout()->content中 17 public function indexAction() 18 { 19 $a = new Article(); 20 $res = $a->fetchAll()->toArray(); 21 $this->view->res = $res; 22 $this->render('index'); 23 } 24 }
通过访问,你可以看到,zend已经为你加载了全部内容:

浙公网安备 33010602011771号