The Yii framework is my personal favorite PHP framework by miles. Today we are going to be learning about using jQuery with the Yii framework. Why is this any different from using jQuery in any other way? Because Yii has some clever built in jQuery functionality that will help speed up your site by reducing jQuery code being loaded on pages where it is not being used.
The clever people at Yii have thought ahead to include jQuery as a part of the framework. Instead of throwing your jQuery between some script tags, we can use Yii’s registerScript functionality to load script only when it needs to be loaded.
For people who aren’t familiar with Yii, this might all sound a bit foreign. For this example, we are going to be using Yii’s registerScript to load our jQuery, which if used normally looks like this:
alert('hello');
});
As I’m sure you know, this would alert “hello” when our document is ready. Now if we use Yii’s registerScript, it looks like this:
Yii::app()->clientScript->registerScript('helloscript',"
alert('hello');
",CClientScript::POS_READY);
?>
You will see that you need to pass 3 things to the Yii::app()->clientScript->registerScript function, firstly a script name, which is not really important; it must just bee unique from any other script name on the same page. We then pass the actual javascript/jQuery. One thing that can become tricky here is the fact that the javascript is in a PHP string, so we often have to escape the quotation marks (since wither the single or double quotes will have been used declaring the string). Finally, we pass the position, which can be POS_READY which puts the script in a jQuery ready block, or POS_HEAD which puts the jQuery in the head section.
The later is usually used for declaring script files, rather than script blocks. That is where the beauty comes into Yii’s jQuery functionality. Why? Because instead of filling your layout with javascript that only gets used on some pages, but is loaded on every page, we can call our javascript only on the views where it is used. To load a javascript file the syntax is much the same, we just replace the script with path to the script and change the position to POS_HEAD, like so:
Yii::app()->clientScript->registerScript('helloscript',Yii::app()->request->baseUrl."/js/helloscript.js"
,CClientScript::POS_HEAD);
?>
You will see we are using Yii’s baseURL function there (Yii::app()->request->baseUrl) to get to the base url to define our path. We can also call the script as a variable:
$ourscript = "alert('hello');";
Yii::app()->clientScript->registerScript('helloscript',$ourscript,CClientScript::POS_READY);
?>
Thats is for our basic Yii/jQuery tutorial. Hope it helps you on your way. If you haven’t checked Yii out, visit them at http://www.yiiframework.com
Happy Yii-ing