Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get url for static image file in Magento 2's javascript files?

Tags:

magento2

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?

like image 688
jurgen Avatar asked Apr 27 '16 09:04

jurgen


1 Answers

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.

like image 81
jurgen Avatar answered Oct 17 '22 07:10

jurgen