From 38205eae6f946cff4073a77d820cca60b38ae690 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Pe=CC=81rez=20Crespo?= <jaime.perez@uninett.no> Date: Wed, 28 Nov 2018 14:04:57 +0100 Subject: [PATCH] Add an asset() function to twig. This function can be used to load an asset from a twig template, adding a "tag" parameter to it with a few dynamic bytes depending on the version of SimpleSAMLphp, or the last modification time of the file if we are running master. This behaves as a cache-buster, forcing browsers to reload assets when a new version of SimpleSAMLphp gets installed. --- lib/SimpleSAML/XHTML/Template.php | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/lib/SimpleSAML/XHTML/Template.php b/lib/SimpleSAML/XHTML/Template.php index d6f4d836c..9b2907fd3 100644 --- a/lib/SimpleSAML/XHTML/Template.php +++ b/lib/SimpleSAML/XHTML/Template.php @@ -143,6 +143,29 @@ class Template extends Response } + /** + * Return the URL of an asset, including a cache-buster parameter that depends on the last modification time of + * the original file. + * + * @param string $asset + * @return string + */ + public function asset($asset) + { + $file = $this->configuration->getBaseDir().'www/assets/'.$asset; + if (!file_exists($file)) { + // don't be too harsh if an asset is missing, just pretend it's there... + return $this->configuration->getBasePath().'assets/'.$asset; + } + + $tag = $this->configuration->getVersion(); + if ($tag === 'master') { + $tag = substr(hash('md5', filemtime($file)), 0, 5); + } + return $this->configuration->getBasePath().'assets/'.$asset.'?tag='.$tag; + } + + /** * Get the normalized template name. * @@ -289,6 +312,9 @@ class Template extends Response ) ); + // add an asset() function + $twig->addFunction(new \Twig_SimpleFunction('asset', [$this, 'asset'])); + if ($this->controller) { $this->controller->setUpTwig($twig); } -- GitLab