Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daltonrooney/3c177e691555ac230b5219089195ab28 to your computer and use it in GitHub Desktop.
Save daltonrooney/3c177e691555ac230b5219089195ab28 to your computer and use it in GitHub Desktop.
Twig Function to get the file mtime in template for HTTP Caching
<?php
$function_filedate = new Twig_SimpleFunction(
'fileDate',
/**
* @param $file_path
* This function generates a new file path with the last date of filechange
* to support better better client caching via Expires header:
* i.e:
* css/style.css -> css/style.1428423235.css
*
* Usage in template files:
* i.e:
* <link rel="stylesheet" href="{{ fileDate('css/style.css') }}">
*
* Apache Rewrite Rule:
*
* RewriteCond %{REQUEST_FILENAME} !-f
* RewriteCond %{REQUEST_FILENAME} !-d
* RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [NC,L]
*
* Apache Document Root MUST be configured without the trailing slash!
*
* @return mixed
*/
function ($file_path) {
$change_date = @filemtime($_SERVER['DOCUMENT_ROOT'].'/'.$file_path);
if (!$change_date) {
//Fallback if mtime could not be found:
$change_date = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
}
return preg_replace('{\\.([^./]+)$}', ".$change_date.\$1", $file_path);
}
);
$twig->addFunction($function_filedate);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment