yii2yii2-module

How to use published asset bundle in a view


I have been looking for information on how to use AssetBundles. After 3days of research I finally found out how use them in the layout file.

In the main.php in layouts I have $moduleAsset = ModuleAsset::register($this);. Then to use an image I have HTML::img($moduleAsset->baseUrl . '/img/picture.jpg', and it works.

The published directory structure is:

| assets
 |-5006d48e // the number given on my machine
   |-css
   |-img

Now I'm trying to use images in the published img directory in a view. I try the $moduleAsset->baseUrl and get an Undefined variable $moduleAsset error.

After another couple of days of searching, I still have no idea how to get this to work.


Solution

  • In view, you can use assetManager->getBundle()

    $path = $this->getAssetManager()->getBundle(ModuleAsset::class)->baseUrl;
    

    I do recommend going trough the basic guides, it saves you days of trial and error