问题
In my controller I have implemented a function for publishing a single asset, such as an image, and return the 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];
}
And then call it in my view like this:
<?= $this->context->publishAsset('@app/assets/img/logo.png') ?>
Working fine, but the function returns the published URL without the 'scheme' in front of it.
For example it returns /assets/7cf54cf2/img/logo.png
instead of http://www.example.com/assets/7cf54cf2/img/logo.png
How can I use the AssetManager or adjust my code so I can get the full URL? I can't find an answer in the documentation, the only solution I have come up with so far is adding it in front manually before returning.
I came onto this problem when trying to use this function in generating HTML for e-mails. Of course URLs in e-mails must contain the scheme in front of it.
Any suggestions other than mine? Thanks!
回答1:
Try using url helper
use yii\helpers\Url;
$publishedPath = $this->assetManager->publish( $path );
return (Url::to($publishedPath[1], true));
回答2:
Would you mind to show your solution how you have got the absolute paths used for your linked css and js files?
My solution is:
\Yii::setAlias('@web', Url::base(true));
\Yii::$app->assetManager->baseUrl = Yii::getAlias('@web/assets');
来源:https://stackoverflow.com/questions/32676450/yii2-assetmanager-published-path-include-url-scheme