Yii中没有模版引擎,本文主要介绍一下Yii渲染页面的原理和使用方法
使用方法篇
/** * 渲染示例 */ public function actionRender() { $this->text = 'Today is a good day'; Yii::app()->clientScript->registerCoreScript('jquery');//加载jquery $this->render('render', array('nick' => 'bennett'));//包含layout $this->renderPartial('render', array('nick' => 'bennett'));//不包含layout,但同时也不会引入jquery }
上面这个方法定义在PostController下,在未使用theme的时候会去
protected->views->post
文件夹下去找render.php
,在使用theme的情况下会优先去找theme对应文件夹下面的文件,如果找不到再去找protected下面的。
在view中可以直接调用Controller中的变量和通过render方法传递的变量<h3>Welcome <?php echo $nick; ?> <h3> <p><?php echo $this->text; ?></p>
layouts的使用
在Yii自带的Controller中声明了一个属性public $layout='column2';
在未使用theme的情况下指定的是protected->views->layouts->column2.php
作为前端的layout
文件。在这个文件中往往是一些html的模版,其中包含了一句<?php echo $content; ?>
这个部分输出的就是Controller中渲染的view。
这个部分主要借助ob_start()
系列函数实现的,有兴趣的可以自行百度。加载css和js
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/my.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/my.js',CClientScript::POS_END);
Yii::app()->clientScript->registerCoreScript('jquery');
把上面的方法在Controller中调用即可。大家可以看到Yii加载jquery的方式不太一样,这个是因为Yii里面已经集成了jquery。接下来说下如何替换Yii中的jquery和解决js依赖。
在main.php中添加如下component
'clientScript' => array(
'scriptMap' => array(
'jquery.js' => 'http://libs.baidu.com/jquery/2.0.0/jquery.js',
'jquery.min.js' => 'http://libs.baidu.com/jquery/2.0.0/jquery.js',//替换系统的jquery
),
'packages'=>array(//自定义package
'jquery' => array(
//'basePath'=>'alias of the directory containing the script files',
'baseUrl'=>'http://libs.baidu.com',
'js'=>array('/jquery/1.9.0/jquery.js'),
//'css'=>array(list of css files relative to basePath/baseUrl),
//'depends'=>array(list of dependent packages),
),
'jquery.ui'=>array(
'baseUrl'=>'http://libs.baidu.com',
'js'=>array('/jqueryui/1.8.22/jquery-ui.min.js'),
'depends'=>array('jquery'),
),
'bootstrap' => array(
'baseUrl'=>'http://libs.baidu.com',
'js'=>array('/bootstrap/3.0.3/js/bootstrap.min.js'),
'css'=>array('/bootstrap/3.0.3/css/bootstrap.min.css'),
'depends'=>array('jquery'),
),
),
'coreScriptPosition' => CClientScript::POS_END,
),
在上面的例子中看到我们自己定义了一些包,我们可以通过Yii::app()->clientScript->registerCoreScript('bootstrap');
来加载自定义的包,如果系统已经加载了这些文件,是不会重复加载的。