yii之layout中column和main文件的关系

在yii创建应用成果之后,在view/layouts/目录下,会产生3个布局页面:

main.php

column1.php

column2.php

因为首次使用的是命令行Shell方式创建的应用,yii本身会创建一个控制器组件:Controller.php 继承了CController控制器,该文件位于/components目录下,

01 //componets/Controller.php文件内容如下
02
03 /**
04 * Controller is the customized base controller class.
05 * All controller classes for this application should extend from this base class.
06 */
07 class Controller extends CController
08 {
09 /**
10 * @var string the default layout for the controller view. Defaults to ‘//layouts/column1′,
11 * meaning using a single column layout. See ‘protected/views/layouts/column1.php’.
12 */
13 public $layout=’//layouts/column1′;
14 … …
15 }

文件里设置了layout的默认页面为: ‘//layouts/column1′,然后再view/layouts/中,column1再次调用main.php视图文件,包裹了两个div层.

1 //column1.php文件内容
2
3 <?php $this->beginContent(‘//layouts/main’); ?>
4 <div class=”container”>
5 <div id=”content”>
6 <?php echo $content; ?>
7 </div><!– content –>
8 </div>
9 <?php $this->endContent(); ?>

包裹的两个div层,默认class名称为container,这可能与自己命名的container有冲突,需要视实际情况做一些调整,加载完main.php文件之后,在包含index.php中的内容即$content中的内容.

如果控制器都是由Gii这个脚手架自动生成,那么所有的控制器都会继承都是继承于Controller而非官方所说的继承与CController控制器,在页面视图渲染,多了一层column1.php中间视图.

所以说yii在 $this->render(‘index’) 一个页面的时候,使用 column1.php 包含 main.php , 再由 main.php 包含 index.php,最后返回内容.(这是针对于继承Controller方式).

而至于column2.php只干什么的呢,貌似是个打酱油的,没有用到.

如果我们想更改默认的layout视图文件,要么直接在Components/Controller.php更改$layout = ‘//layouts/newlayout_name’,要么控制器继承时,直接 extends CController 而不是Controller,然后配置config/main.php:

1 //第二种方式 更改config/main.php,添加layout应用级别layout
2 return array(
3 … …
4 ‘name’ => ‘Web Application’,
5 ‘layout’ => ‘newlayout_name’,
6 … …
7 )

然后在控制器里调用:

1 //TestController 自定义一个测试控制器
2 class TestController extends CController{
3 … …
4 }

当然你也可以直接在控制器里设置layout属性,覆盖默认的layout,使得视图渲染更灵活.此处只是为说明 /view 下layouts/中,main.php和column1.php,以及index.php之间的关系.

相关文章: 

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)