3

I have a image in a module within the following structure: vendor/myvendorname/mymodulename/assets/img/delete-icon.png

I need to add an <img> to the page via JavaScript, and it may have the src attribute pointing to that delete-icon.png.

$("#delete").attr("src", "?");

How can I reference the image if it will be put in an asset directory created by Yii? What is the way to get this path?

felipe.zkn
  • 2,012
  • 7
  • 31
  • 63

1 Answers1

5

As soon as you register the AssetBundle it is possible to fetch its baseUrl. In the rest of the view you can then use that to get to your images:

$assets = MyAssetBundle::register($this);
$imagePath = $assets->baseUrl . '/img/delete-icon.png';

$this->registerJS(<<<JS
   $("#delete").attr("src", "$imagePath");
JS
  );
Blizz
  • 8,082
  • 2
  • 33
  • 53