Magento 2 – How to Specify Image Path in JavaScript Without Hardcoding

javascriptmagento2

I'm using webicon script in my theme to use svg/png as icons. This is the code from my jQuery widget:

_create: function () {
    $(document).webicons({
        icons: {
            tile: 'http://magento2.dev:8888/project/pub/static/frontend/vendor/theme/en_US/images/tile.png',
            user: '../images/user.png'
        }
    });
}

If I hardcode the whole path the image displays correctly, second one doesn't display. I've tried other approaches that also wont display. Is there a way to do this directly in JS? I know I could load the path with data-mage-init in PHP and pass it in with config options, but I'd like to know if anyone found a way to do this directly in JS?

Best Answer

This is not a solution, but it is an explanation on why you SHOULD use the data-mage-init approach.
You kind of HAVE TO provide the calculated image paths via a template or something because of the theme fallback mechanism.
Also, if you provide the full path to something in the pub/static folder your widget will crash if the static resources are not deployed.
You need something that generates the image in pub/static before using it. passing it as a parameter from a template will ensure that.

Related Topic