This tutorial is about magento 2 Get base url in js file. First of all i assume that you are familiar with magento 2 and hence you are at this level where you want to know how to get base url from js file in magento 2. Above all if you are not familiar with advance magento concepts and are looking for basics,please look for magento 2 basic tutorials.
So lets start our tutorial and focus on our topic. For example if you want to get base url from .js file and append it with your module controller link from. How can we do it? It is almost impossible to use block to get the base url.
Get base url
So we will look at the way how we can get base url. to do that,paste the following code in your routes.xml file
Where frontname is your routes.xml file frontname.
Since it is necessary,you have to pass your frontname from routes.xml file instead of module name(namespace_module).
Furthermore you can lookup your routes.xml file from
It might work for some and might not for others.
Further more Add this code in phtml file:
having done that you can use this base url in js file by id :
It is a quite useful and tested trick. So i thought to share it.
There is another approach for this task.Having said that it may too be useful.
You should pass url to js(widget).Url is a parameter of js widget.And put script below to your template where you want to.
"dataUrl": "<?php echo $block->getBaseUrl(); ?>"
Another simple approach is
window.testUrl = <?php echo json_encode($block->getBaseUrl()); ?>
Using your custom js you can have easy access to window.testUrl global variable.
That’s it from this tutorial. I hope it serves the purpose.
Since these tutorials are for learning purpose please feel free to drop any suggestions or queries in comments section. That will definitely be highly appreciated.
Give A Rating
Average Rating / 5. Vote Count