Reputation: 247
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?
Upvotes: 9
Views: 15786
Reputation: 7752
In JavaScript it's available with require.toUrl('images/image.png')
.
Upvotes: 15
Reputation: 8366
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
Upvotes: 1
Reputation: 247
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.
Upvotes: 3