Registering Javascripts In Yii
Posted:
Tuesday, May 1st, 2012Last modified:
Thursday, April 9th, 2015Overview
How to add jQuery and other Javascripts to Yii applications.
How To Add Scripts to Your Yii View
Jquery scripts must be registered with the application view using the CClientScript.
Registering a Snippet of Javascript
Suppose we want to add the following snippet of code to our view immediately before the closing body tag.
<script type="text/javascript"> /*<![CDATA[*/ jQuery(function($) { $("a[rel^='prettyPhoto']").prettyPhoto({'social_tools':''}); }); /*]]>*/ </script>
We register the snippet using the registerScript method. The registerScript method has the following signature:
$script = '$("a[rel^=\'prettyPhoto\']").prettyPhoto({\'social_tools\':\'\'});'; Yii::app()->clientScript ->registerScript('prettyPhoto',$script,CClientScript::POS_READY);
registerScript Arguments
The registerScript method has the following signature:
public CClientScript registerScript(string $id, string $script, integer $position=4)
- $id A unique identifier for this script.
- $script A string containing the script or snippet.
- $position Sets the position of the Javascript.
- CClientScript::POS_HEAD : the script is inserted in the head section right before the title element.
- CClientScript::POS_BEGIN : the script is inserted at the beginning of the body section.
- CClientScript::POS_END : the script is inserted at the end of the body section.
- CClientScript::POS_LOAD : the script is inserted in the window.onload() function.
- CClientScript::POS_READY : the script is inserted in the jQuery's ready function.
References
Available Wiki Topics
The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.