in reply to Re^2: Best practices: Generating HTML content
in thread Best practices: Generating HTML content

Hi Dallaylaen,

TT does not cache compiled templates. This can be overcome but not easily.

Just to clarify, I assume you mean that the Template Toolkit does not cache compiled templates *persistently* if they originated as a reference to a string, as you showed.

See the documentation on "Caching and Compiling Options".

You can cache compiled templates in memory explicitly without even processing them using template():

$ perl -MTemplate -wE ' my $tt = Template->new; my $compiled = $tt->template(\"In-place [% foo %] query\n"); my $answer = 40; $tt->process( $compiled, {foo => $answer++} ) for 0..2; ' In-place 40 query In-place 41 query In-place 42 query
And of course you can cache persistently between program runs if you use the right configuration options (and use a template file or filehandle):
my $tt = Template->new( INCLUDE_PATH => '/some/path', COMPILE_DIR => '/other/path', COMPILE_EXT => '.compiled', ); my $file = 'foo.tt'; my $data = { foo => 42 }; $tt->process( $file, $data ) or die $tt->error; # Template will be compiled and cached at '/other/path/foo.tt.compiled +' # and that file will be used until '/some/path/foo.tt' changes
I'm sure you knew this, just clarifying for future readers...


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^4: Best practices: Generating HTML content
by Dallaylaen (Chaplain) on Dec 24, 2017 at 18:03 UTC

    Thanks 1nickt,

    I only meant im-memory caching during the application lifetime. Not between runs (that's for sure not what one wants to do in a module).

    Upon reading your reply, I rushed to revisit my code that dealt with caching scalar reference templates. What I found there was exactly my $compiled = $tt->template(\$in_memory); sequence - at which I arrived after trying to utilize Template::Provider.

    So caching compiled templates is indeed simple. It's just not quite obvious from documentation. And the possible speed penalty is a pitfall that's worth mentioning.