Skip to content

Instantly share code, notes, and snippets.

@AugustMiller
Last active February 19, 2019 00:53
Show Gist options
  • Save AugustMiller/6c9f07984d1781df9f7e19467f9c5266 to your computer and use it in GitHub Desktop.
Save AugustMiller/6c9f07984d1781df9f7e19467f9c5266 to your computer and use it in GitHub Desktop.
Basic asset cache busting plugin for Craft CMS.
<? namespace Craft;
# craft/plugins/helpers/HelpersPlugin.php
class HelpersPlugin extends BasePlugin
{
public function getName()
{
return Craft::t('Helpers');
}
public function getVersion()
{
return '1.0';
}
public function getDeveloper()
{
return 'oof. Studio';
}
public function getDeveloperUrl()
{
return 'http://oof.studio/';
}
}
<? namespace Craft;
# craft/plugins/helpers/variables/HelpersVariable.php
class HelpersVariable
{
/*
* Get the text content of an asset in the public directory
*/
public function inlineAsset(String $asset)
{
$file = $this->releasePath() . 'public/assets/' . $asset;
return IOHelper::getFileContents($file);
}
/*
* Dynamically fetch the app's root directory
*/
public function releasePath()
{
return str_replace('craft/plugins/helpers/variables', '', __DIR__);
}
/*
* Get the last modified date for a static asset
*/
public function assetModificationTime(String $asset)
{
$file = $this->releasePath() . '/public/' . $asset;
return IOHelper::getLastTimeModified($file)->getTimestamp();
}
/*
* Get a public URL for an asset in the public directory
*/
public function assetUrl($asset, $params = [])
{
return UrlHelper::getUrlWithParams($asset, $params);
}
/*
* Get the filesystem path for an uploaded file
*/
public function assetPath(AssetFileModel $asset)
{
$source = $asset->getSource();
if ($source->type != 'Local')
{
throw new Exception(Craft::t('Paths not available for non-local asset sources'));
}
$sourcePath = $source->settings['path'];
$folderPath = $asset->getFolder()->path;
return $sourcePath . $folderPath . $asset->filename;
}
public function includeCss($asset)
{
$mtime = $this->assetModificationTime($asset);
$url = $this->assetUrl($asset, ['mtime' => $mtime]);
craft()->templates->includeCssFile($url, true);
}
public function includeJs($asset)
{
$mtime = $this->assetModificationTime($asset);
$url = $this->assetUrl($asset, ['mtime' => $mtime]);
craft()->templates->includeJsFile($url);
}
}
{# Add ?mtime=1234567890 to the asset url: #}
{{ craft.helpers.includeCss('/assets/css/app.css') }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment