From e0792ca8b4d11f9fcb693246a6c612f8230b66f9 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 4 Sep 2012 14:43:54 +0100 Subject: [PATCH] Added support for transparent template caching. --- Template.pm | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Template.pm b/Template.pm index 7763998..65a04aa 100644 --- a/Template.pm +++ b/Template.pm @@ -183,6 +183,10 @@ BEGIN { # to mark the location of an ordinal specifier. %o is ignored if it # does not immediately follow a digit field. Defaults to "%a, %d %b %Y %H:%M:%S" # - `blockname` If set, allow blocks to be specified by name rather than id. +# - `usecache` If true, template files are cached as they are loaded. This will increase memory use, but +# can make template operations faster in situations where the same template needs to be used +# repeatedly, but explicity preloading can't be performed. Template files are reloaded if the +# file mtime has changed since the last load to avoid stale cache entries. This defaults to true. sub new { my $invocant = shift; my $class = ref($invocant) || $invocant; @@ -199,6 +203,7 @@ sub new { "entities" => $entities, "utfentities" => $utfentities, "blockname" => 0, + "usecache" => 1, @_, }; @@ -482,6 +487,12 @@ sub load_template { next; } + my $filemtime = (stat($filename))[9]; + + # If caching is enabled, and the times match, the file has been loaded before + return $self -> process_template($self -> {"cache"} -> {$name} -> {"template"}, $varmap, $nocharfix) + if($self -> {"usecache"} && $self -> {"cache"} -> {$name} -> {"mtime"} == $filemtime); + # Try the load and process the template... if(open(TEMPLATE, "<:utf8", $filename)) { undef $/; @@ -489,6 +500,10 @@ sub load_template { $/ = "\n"; close(TEMPLATE); + # Cache the template if needed. + $self -> {"cache"} -> {$name} = { "template" => $lines, "mtime" => $filemtime } + if($self -> {"usecache"}); + # Do variable substitution $self -> process_template(\$lines, $varmap, $nocharfix);