Use UrlManager to create ajax urls in Javascript file

Hi,

I’m learning about using AssetBundles to publish js files.

is there a way to use UrlManager to create the ajax urls in your js files?

It looks like AssetBundle has a publish method where you can specify a PHP callback to process the file before it’s published. So I guess I could create some sort of templating system where any string that matches some sort of placeholder syntax would get processed as a url and converted to a url by UrlManager.

But I was wondering if there was a built-in "Yii2" way of doing that.

Anyone know?

-Charlie

Sometimes, I do it using this approach.

In my view file I write something like this:




<script>


var apiURL= '<?php echo Yii::$app->params['apiURL']; ?>';


</script>

When view file is rendered, inside the scirpt tags I will have something like this:




<script>


var apiURL= 'http://my.api.com';


</script>

Because apiURL is global variable in JS, you can access to this variable from any JS file you load (additionally all my JS files are loaded at the end).

1 Like

That seems like a good approach. Thanks.