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

9 followers

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.

Total 4 comments

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

"$('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
redguy 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