2

How to correctly get site url inside js file within magento module?

It should contain protocol (http | https) and domain name.

No path required.

Format http://example.com

white-imp
  • 611
  • 12
  • 28

2 Answers2

6

If you are following best practices and using Require JS to load your Javascript this is a simple task. If you are not following best practices, now is the time to start ;)

I believe the best way is to pass the URL to the JS file via the PHTML template like so:

Template file

<script type="text/x-magento-init">
    {
        "*": {
            "Magento_Ui/js/core/app": {
                "components": {
                    "tenLooks": {
                        "component": "Ben_AppTest/js/ten-looks",
                        "dataUrl": "<?php echo $block->getViewFileUrl('Ben_AppTest::js/data.js'); ?>"
                    }
                }
            }
        }
    }
</script>

Javascript File

define(['uiComponent'], function(Component) {
    'use strict';

    return Component.extend({
        initialize: function() {
            console.log(this.dataUrl);
        }
    });
});

enter image description here

Ben Crook
  • 15,685
  • 3
  • 52
  • 104
4

You should not get the base url in your JS files.
Write your js files are ui widgets and the base url should be a parameter.
Then pass that parameter from the template that uses the ui widget.

Marius
  • 197,939
  • 53
  • 422
  • 830
  • Thanx, but it's quite confusing for me. Do you have any example of such widget? – white-imp Jul 06 '16 at 13:14
  • Here is an example of how a widget is created : https://github.com/magento/magento2/blob/develop/app/code/Magento/ConfigurableProduct/view/frontend/web/js/configurable.js (the configurable products ui widget), And here is how it is called with parameters from a template: https://github.com/magento/magento2/blob/develop/app/code/Magento/ConfigurableProduct/view/frontend/templates/product/view/type/options/configurable.phtml#L33 – Marius Jul 06 '16 at 13:18