Yii2: AssetManager appendTimestamp to manually published files

Created on 4 Mar 2019  路  5Comments  路  Source: yiisoft/yii2

I'm attempting to use the AssetManager to manually publish some static files (neither CSS or JS), but when I call AssetManager::publish() it does not append the timestamp. I have set $appendTimestamp = true

Semantically, I would expect a function called publish, which returns a URL, to give a final URL with all amendments

Furthermore, both the parameter name used to append the timestamp, 'v', and the code itself, are hardcoded deep in the AssetManager::getAssetUrl(), so it's not extensible

It appears that lots of people are hitting this issue. Could you at the least open this up for extension by separating the code into a protected or public function, like AssetManager::appendTimestamp($url)

It would also be nice to have a public $appendTimestampParam = 'v' so that this can be configured too

I love your framework, but I often run into situations where code is not separated into functions or variables. Extending the framework often requires copying copying whole chunks of code into overridden functions, or just replacing files wholesale

bug

All 5 comments

How do you call AssetManager::publish() exactly?

Thanks for posting in our issue tracker.
In order to properly assist you, we need additional information:

  • When does the issue occur?
  • What do you see?
  • What was the expected result?
  • Can you supply us with a stacktrace? (optional)
  • Do you have exact code to reproduce it? Maybe a PHPUnit tests that fails? (optional)

Thanks!

_This is an automated comment, triggered by adding the label status:need more info._

Here is my makeshift function that publishes a file using the asset manager

/**
 * Publish file using asset manager and return URL
 *
 * @param string $filename File to publish
 * @return string URL of published file
 *
 * @throws InvalidConfigException
 */
public function publish($filename) {

    $assetManager = Yii::$app->assetManager;
    $sourceFilename = Yii::getAlias($filename);

    // Publish file, I was hoping this would append the timestamp
    list($publishedFilename,$url) = Yii::$app->assetManager->publish($sourceFilename);

    // Append timestamp if necessary, code from AssetManager::getAssetUrl()
    if (
        $assetManager->appendTimestamp &&
        ($timestamp = @filemtime($publishedFilename)) > 0
    ) {
        $url .= '?v=' . $timestamp;
    }

    return $url;
}

Here is my relevant AssetManager config:

from common

    'assetManager' => [
        // Cache bust newer assets
        'appendTimestamp' => true,
    ],

from frontend

    'assetManager' => [
        'basePath' => '@frontend-assets-dir', // frontend/web/assets
        'baseUrl' => '@frontend-assets-url', //  example.com/assets
    ],

@crisps-for-breakfast try code from master. Was your issue fixed?

That got it! Thank you so much :)

Was this page helpful?
0 / 5 - 0 ratings