Yii自定义布局的实现

PHP 林涛 9368℃ 0评论

Yii创建应用后会自动生成布局,如果没有指定布局yii框架会逐层向上寻找布局文件,所以自定义布局即要在当前模块和系统默认布局之间创建。步骤如下:

· 使用脚手架创建模块

1> 在config中main.php中开启gii,即:把下面的注释去掉’modules’=>array(


// uncomment the following to enable the Gii tool
/*
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'Enter Your Password Here',  //此处设置登陆脚手架的密码
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
*/
),

 输入gii地址(如:shop项目,http://localhost/shop/index.php?r=gii/default/login),进入gii密码界面;

a,输入密码(上面“1>”设置好的);
b,进入页面,选择最后一个布局创建(Module Generator);

c,然后在Module ID的输入框中,输入你的模块名称,如:houtai 再点击Preview 继续点击Generate;再回protected查看是否存在modules/houtai文件,存在就OK完成自动创建gii的houtai模块了。
开启模块调用功能,把houtai加入main.php的modules中,即,在modules中加入”houtai”元素值;如下:

'modules'=>array(
// uncomment the following to enable the Gii tool
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'******' // 这里数据登陆gii的密码,
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
'sadmin',
),

·后台layout文件的调用与设置

1> 由于项目(下方统称为前端页),也有一个对应的layout;即:实际盘根路径\shop\protected\components\Controller.php和你的实际盘根路径\shop\protected\views\layouts\column1.php两个调用和设置文件了。在默认状态下,gii创建的sadmin(下方统称后台)如果用render开启布局渲染的话,会直接把前端页的父类布局内容调出来。当然这不是我们要的结果!

所以,我们再设置一下,让后台调用新的布局。

设置方法:

1)直接复制前端布局的相应2个文件,粘进sadmin对应文件夹,文件夹名肯定要自己新增的,效果如下:
a> sadmin\components\Controller.php
b> sadmin\views\layouts\column1.php(column1.php可任意换名,如xx.php)

2)修改houtai\components\Controller.php中,把
public $layout=’//layouts/column1′;中开头的双斜扛,去掉一个(因为://,则默认会加载protected/view/layouts/column1.php这个layout;),

column1改成你自己新名字(xx.php);效果如下:
public $layout=’/layouts/xx’;

column1下的$this->beginContent(‘//layouts/main’); 也需要修改为:$this->beginContent(‘/layouts/main’);(去掉一个’/’) 
三、column1.php设置

跟模板的替换原则一样,用$content做变量,加载页面时,换成render渲染的内容。

另外,css、js、images等文件的调用:

在congfig目录下创建自定义函数的文件,定义css等文件的路径,如下:


define("SITE_URL", "http://localhost/yii/diyikaoshi/");

 define("SADMIN_CSS_URL", SITE_URL."assets/sadmin/css/");

然后在视图中协商定义的常量,如:


<link href="<?php echo SADMIN_CSS_URL;?>layout.css" rel="stylesheet" type="text/css">

原始内容参考:http://yd514.iteye.com/blog/1933392

如需转载请注明: 转载自26点的博客

本文链接地址: Yii自定义布局的实现

转载请注明:26点的博客 » Yii自定义布局的实现

喜欢 (0)
发表我的评论
取消评论

表情