Looking for Craft 3 Support? Asset Rev for Craft 3
A Twig extension for CraftCMS that helps you cache-bust your assets by appending query string or swapping out asset file names with their revved version, as they are defined in a JSON manifest file.
Manifest files would most likely be generated by Grunt/Gulp modules, such as grunt-filerev-assets or gulp-rev.
In order to speed up the load time of your pages, you can set a far-future expires header on your images, stylesheets and scripts. However, when you update those assets you'll need to update their file names to force the browser to download the updated version.
Using a manifest file is the recommended approach - you can read up on why using query strings isn't ideal here.
Copy the assetrev
folder to your craft/plugins
directory and activate it from the Craft plugin settings page. Once activated, you may want to specify a custom path to your asset manifest file within the plugin configuration.
The plugin comes with a config.php
file that defines some sensible defaults.
If you want to set your own values you should create a assetrev.php
file in your Craft config directory. The contents of this file will get merged with the plugin defaults, so you only need to specify values for the settings you want to override.
manifestPath
is where Craft should look for your manifest file. Non-absolute paths will be relative to the base path of your Craft installation (whatever CRAFT_BASE_PATH
is set to).
assetsBasePath
is the the base path to your assets. Again, this is relative to your craft base directory, unless you supply an absolute directory path.
assetUrlPrefix
will be prepended to the output of rev()
.
Note: You can use any environment variables that you may have set in your general.php
config file in any of these configuration values.
<?php
return array(
'*' => array(
'manifestPath' => 'resources/assets/assets.json',
'assetsBasePath' => '../public/build/',
'assetUrlPrefix' => '{baseUrl}',
),
);
Once activated and configured you can use the rev()
function in your templates.
<link rel="stylesheet" href="{{ rev('css/main.css') }}">
css/main.css
will be replaced with the corresponding hashed filename as defined within your assets manifest .json file.
If the contents of your manifest file are...
{
"css/main.css": "css/main.a9961d38.css",
"js/main.js": "js/main.786087f5.js"
}
then rev('css/main.css')
will expand to css/main.a9961d38.css
.
If the plugin can't find a valid manifest file it will fall back to appending a query string to your file, based on the time it was last modified. In this scenario rev('css/main.css')
will expand to something like css/main.css?1473534554
.