How to include image in Yii2 module

1k Views Asked by At

Cannot provide correct path to image in view inside of Yii2 module. Script and styles are loaded correctly.

module structure:

|-assets
|  ↳Asset.php
|-controllers
|-models
|-public
| |-css
| |  ↳styles.css
| |-js
| |  ↳script.js
| |-img
|    ↳image.gif
|-views
|  ↳view.php
|-Module.php

Asset.php:

class Asset extends AssetBundle {
    public $sourcePath = '@app/modules/scrapy/public';
    public $css = ['css/styles.css'];
    public $js = ['js/scrapy.js'];
}

fragment of Module.php:

public function init() {
    parent::init();
    $this->setAliases([
        '@modulename' => '@app/modules/module',
    ]);
}

public function getViewPath() {
    return '@modulename/views/';
}
1

There are 1 best solutions below

2
ustmaestro On BEST ANSWER

In your view file register the module asset:

<?php
// include module asset class
use app\modules\mycoolmodule\assets\Asset;

// register module asset in view and store it to a variable
$myAssetBundle = Asset::register($this);
?>

Now to access the image from img asset folder:

<img src="<?= $myAssetBundle->baseUrl . '/img/image.gif'; ?>" alt="image" />

So what you want is $myAssetBundle->baseUrl dynamic url of your asset bundle.

PS: There are differences between app assets and module|widgets assets: https://github.com/yiisoft/yii2/issues/3048