在我的 Controller 中,我实现了发布单个 Assets (例如图像)并返回 URL 的功能:
/**
* Publish an asset and return url
*
* @param $src
*
* @return mixed
*/
public function publishAsset( $src ) {
$path = Yii::getAlias( $src );
if ( ! $this->assetManager ) {
$this->assetManager = new AssetManager();
}
$return = $this->assetManager->publish( $path );
return $return[1];
}
然后在我的 View 中这样调用它:
<?= $this->context->publishAsset('@app/assets/img/logo.png') ?>
工作正常,但该函数返回已发布的 URL,前面没有“方案”。
例如它返回 /assets/7cf54cf2/img/logo.png
而不是 http://www.example.com/assets/7cf54cf2/img/logo.png
如何使用 AssetManager 或调整我的代码以获得完整的 URL? 我在文档中找不到答案,到目前为止我想出的唯一解决方案是在返回之前手动将其添加到前面。
我在尝试使用此功能为电子邮件生成 HTML 时遇到了这个问题。当然,电子邮件中的 URL 必须在其前面包含方案。
除了我还有什么建议吗?谢谢!
最佳答案
尝试使用 url 助手
use yii\helpers\Url;
$publishedPath = $this->assetManager->publish( $path );
return (Url::to($publishedPath[1], true));
关于Yii2 AssetManager 发布路径包括 URL 方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676450/