I needed to register CSS files with priority , so my file overwrite each other into the correct order.
I know there is other solution for that i did some research, but my approach is more easy too implement and there is no regexp involved or string parsing, we always benefit from using low cpu & memory
NOTE: Yii will render all registed-js-css-script-style BEFORE the TAG <title> inside the <head>.
<link> inside a view can be rendered before of after registered script depending where is the tag <title>.
P.S. love is everywhere
TODO:
-
less support
-
baddPackage()
-
bregisterJSFile()
Usage :
-
All script not registered with bregisterCSSFile() will have a priority of 100 by default
-
here some example of css file registered with bregisterCSSFile()
Yii::app()->clientScript->bregisterCSSFile(1,"/css/base/css1.css","screen");
Yii::app()->clientScript->bregisterCSSFile(100,"/css/base/css2.css");
Yii::app()->clientScript->bregisterCSSFile(500,"/css/base/css3.css");
Implementation :
NOTE: in the future i will try to remove the need of adding a function into a base controller class.
- Config
'components'=>array(
'...'
'clientScript'=>array(
'behaviors'=>array(
'thecatisattackingmymouse'=>array(
'class'=>'path.to.BClientScript',
-
YourController.php or a BaseController , Yii auto generate app/protected/components/Controller.php as base controller.
-
Define that new function
protected function afterRender($view,&$output)
{
Yii::app()->clientScript->sortCSSFile();
return parent::afterRender($view,$output);
}
BClientScript.php :
- Source Code
3180
class BClientScript extends CBehavior
{
private $cssFiles = array();
function bregisterCSSFile($priority,$url,$media='')
{
$this->cssFiles[$url]=$priority;
$this->getOwner()->registerCSSFile($url,$media);
}
function sortCSSFile()
{
$cssFiles = Toys::getCComponentVar($this->getOwner(),'cssFiles');
// add file registered normaly with clientScript->registeredCSSFile()
$this->cssFiles = array_merge($cssFiles,$this->cssFiles);
// all file registered with clientScript->registeredCSSFile()
// will get a priority of 100
foreach($this->cssFiles as &$value)
{
if(!is_numeric($value))
$value = 100;
}
// sort the file with priority
asort($this->cssFiles);
// merge back new array with old value
$cssFiles = array_merge($this->cssFiles,$cssFiles);
// free mem
$this->cssFiles = null;
Toys::setCComponentVar($this->getOwner(),'cssFiles',$cssFiles);
}
}
Toys :
- Just parse that class inside the BClientScript.php
class Toys
{
public static $value = null;
static function getCComponentVar(CComponent $CComponent,$name)
{
return $CComponent->evaluateExpression('$this->'.$name);
}
static function setCComponentVar(CComponent $CComponent,$name,$value)
{
Toys::$value = $value;
$CComponent->evaluateExpression('($this->'.$name.' = Toys::$value)');
Toys::$value = null;
}
public function init(){}
}