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="" />


<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.

4 0
Viewed: 34 275 times
Version: 1.1
Category: Tips
Written by: sensorario
Last updated by: sensorario
Created on: Sep 21, 2011
Last updated: 12 years ago
Update Article


View all history

Related Articles