9

I need to get a URL for an image stored in my theme (app/design/frontend/MyVendor/MyTheme/web/images/image.png) from a javascript file (payment.js).

In PHP I can do it like this:

<?php echo $block->getViewFileUrl('images/image.png') ?>

How can I do this in JavaScript?

AlBlue
  • 23,254
  • 14
  • 71
  • 91
jurgen
  • 247
  • 1
  • 2
  • 9

3 Answers3

15

In JavaScript it's available with require.toUrl('images/image.png').

Holly
  • 7,462
  • 23
  • 86
  • 140
3

I did it by adding variable to window from *.phtml file:

<script>
    window.imgpath = '<?php echo $block->getViewFileUrl('images/image.png') ?>';
</script>

and reading that variable from window in *.js:

function someFunction() {
    var imgPath = window.imgpath;
}

Actually, in Magento core files I saw examples of such things.

jurgen
  • 247
  • 1
  • 2
  • 9
1

A better way to do it is:

.phtml file

<script type="text/x-magento-init">
    {
        "*": {
            "Module/js/example":"<?php echo "test" ?>"
        }
    }        
</script>

.js file

define([], function () {
    var mageJsComponent = function(config)
    {
        console.log(config);
    };

    return mageJsComponent;
});

Doc: http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/custom_js.html

Claudiu Creanga
  • 8,031
  • 10
  • 71
  • 110