phpyii2yii-modules

Yii 2: Using module's image declared as asset


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?


Solution

  • 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
      );