如何在 Yii2 模块中包含图像

How to include image in Yii2 module

无法在 Yii2 模块的视图中提供正确的图像路径。脚本和样式已正确加载。

模块结构:

|-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'];
}

Module.php 的片段:

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

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

在您的视图文件中注册模块资产:

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

现在从 img 资产文件夹访问图像:

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

所以你想要的是你的资产包的 $myAssetBundle->baseUrl 动态 url。

PS: app 资产和 module|widgets 资产之间存在差异: https://github.com/yiisoft/yii2/issues/3048