Skip to content

Instantly share code, notes, and snippets.

@Stoffo
Last active May 24, 2020 07:47
Show Gist options
  • Save Stoffo/4cd812948bb1020e7d91 to your computer and use it in GitHub Desktop.
Save Stoffo/4cd812948bb1020e7d91 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