Yii注册css和js(附简单翻译)


Their are many places where we have css & javascript files, like in css folder which is outside the protected folder, css & js files of extension & widgets which we need to include externally sometime when use ajax a lot, js & css files of core framework which also we need to include externally sometime. So their are some ways to do this.

Include core js files of framework like jquery.js, jquery.ui.js
(引用框架的核心js文件时,如jquere,jquery.ui)

<?php 
Yii::app()->clientScript->registerCoreScript('jquery');     
Yii::app()->clientScript->registerCoreScript('jquery.ui'); 
?>

Include files from css folder outside of protected folder.
(引用脚本或样式文件所在目录位于protected目录之外时)

<?php 
Yii::app()->clientScript->registerCssFile(Yii::app()->baseUrl.'/css/example.css');
Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl.'/css/example.js');
?>

Include css & js files from extension or widgets.Here fancybox is an extension which is placed under protected folder. Files we including has path : /protected/extensions/fancybox/assets/(如果引用的来自于扩展或微件。比如fancybox是一个位于protected目录下的扩展。我们准备引用的文件位于/protected/extensions/fancybox/assets/目录下)

<?php
// Fancybox stuff.
$assetUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.fancybox.assets'));
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.fancybox-1.3.4.pack.js'); 
Yii::app()->clientScript->registerScriptFile($assetUrl.'/jquery.mousewheel-3.0.4.pack.js'); 
?>

Also we can include core framework files: Example : I am including CListView js file.
(同样我们可以引用框架的核心文件,如:我引用CListView的js文件)

<?php
$baseScriptUrl=Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets'));
Yii::app()->clientScript->registerScriptFile($baseScriptUrl.'/listview/jquery.yiilistview.js',CClientScript::POS_END);  
?>

We need to include js files of zii widgets or extension externally sometimes when we use them in rendered view which are received from ajax call, because loading each time new ajax file create conflict in calling js functions.

For more detail Look at my blog article
http://stackoverflow.com/questions/1998449/include-css-javascript-file-in-yii-framework

普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress