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:

Yii::app()->getClientScript()->registerCssFile($filename);

or maybe this:

Yii::app()->getClientScript()->registerScriptFile($filename);

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

or

<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(
    'js/script1.js',
    'js/script2.js'
);
$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/'.

Important

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

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

Revisions

View all history

Related Articles