We are going to deploy the new yiiframework.com website on March 23, 2018 from 8:00 to 12:00 UTC.
Website and Yii documentation will not be available in this time frame. Check the news for more details.

Yii 1.1: Send asset folder path to a javascript of a widget


When you develop a widget, you could need one image that is in the assets folder, you can use it simply within a css. You can load a css or javascript script doing this:


or maybe this:


But, when your widget javascript code needs an image that is in the assets folder, you need the image path! We are talking about:

<img src="http://www.example.com/webapp/assets/123124de/widget/image.png" />


<img src="/webapp/assets/123124de/widget/image.png" />

This happens when a javascript code manipulate the DOM. If your widget use a css, it can get images simply by url(../images/image.png); because your image is in the same assets folder of the css.

So. You can register a script that creates a global javascript variable. Then, you can use this variable inside the javascript code that needs this value:

$scripts = array(
$assetFolder = Yii::app()->getAssetManager()->publish('assets');
$script = 'assetUrl = "' . $assetFolder . '";';
Yii::app()->getClientScript()->registerScript('_', $script, CClientScript::POS_HEAD);
foreach ($scripts as $file)
    Yii::app()->getClientScript()->registerScriptFile($file, CClientScript::POS_END);

Now, in your script1.js, you can use the variable assetUrl. For example, if you do alert(assetUrl); you'll see the path of this assets, ıe. '/assets/234hn43/'.


To do this in more widgets or extensions, use unique javascript var name like [extensionName]AssetUrl.

Total 4 comments

#5258 report it
sensorario at 2011/09/27 04:44am

"$('body').data('MyWidgetAssetsUrl',{$assetsFolder});" is a jquery function and means that you have loaded jquery and DOM model. If you see, I set assetUrl in

tag and var is global:

and in PS_END I can load javascript files that uses this var before dom is loaded:

I dont want to wait dom load. You can see my lyiightbox widget to see this tips in action.

#5256 report it
yiqing95 at 2011/09/26 11:07pm
great ! it is helpful

nice, good job, i v thought if i could hidden the $assetFolder to somewhere , "$('body').data('MyWidgetAssetsUrl',{$assetsFolder});" then register it ;

#5205 report it
sensorario at 2011/09/22 04:01am
corrected variable name

Right! I'll correct also the widget when I use this technique. Thank you!

#5200 report it
Maciej Liżewski at 2011/09/22 03:25am
variable name

Just to make it more clear: rather use JS variable with more unique name, like [widget name]_assetUrl, or you will end up in hard to trace errors when one widget will override its value from other widget... :)

Leave a comment

Please to leave your comment.

Write new article