unchanged
Title
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:
~~~
[php]
Yii::app()->getClientScript()->registerCssFile($filename);
~~~
or maybe this:
~~~
[php]
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:
~~~
[php]
<img
src="http://www.example.com/webapp/assets/123124de/widget/image.png"
/>
~~~
or
~~~
[php]
<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:
~~~
[php]
$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.[extensionName]AssetUrl.