Search code examples
yii2assets

Yii2 AssetManager published path include URL scheme


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!


Solution

  • Try using url helper

    use yii\helpers\Url;
    
    $publishedPath = $this->assetManager->publish( $path );
       return (Url::to($publishedPath[1], true));