Say you have a js file in your module: MyModule/view/frontend/web/js/
. How would you reference the image found in MyModule/view/frontend/web/images/
?
A solution would be this one, but looks wrong and inserts global variables:
<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;
}
Update, using with widgets:
#template.phtml:
<script type="text/x-magento-init">
{
"*": {
"mywidget": {
"marker_image": " <?php echo $block->getViewFileUrl('images/map_pin.png'); ?> "
}
}
}
</script>
in my mywidget.js:
define([
'jquery',
'jquery/ui'
], function ($) {
'use strict';
$.widget('company.mywidget', {
_create: function(){
console.log(this.options.marker_image); //OUTPUTS THE RIGHT VALUE IN THE CONSOLE
return this.options.marker_image; //THIS IS THE BIT THAT DOESN'T WORK
},
test_string: "this appears fine" //IF IT IS A STRING THEN IT IS FINE
});
return $.company.mywidget;
});
in my main js file where all comes together:
require([
'jquery',
'mywidget'
],
function($,mywidget){
$(document).ready(function(){
data = new mywidget();
console.log(data) // returns an object where I cannot find my paramater, but test_string is there.