Presentation: Template::Toolkit as a cheap API

I’m just going to copy and paste my slides from this Lightning Talk delivered at the 2016 Dutch Perl Workshop. Lightning talks have a maximum of 5 minutes, and I wanted to do something light and fun. These talks are usually at the end of the day and having something that I could deliver with some energy and humor really helped.
The point of this presentation is that Perl allows you to do things that just work, even if you are ‘cheating’ to make it work. In this instance, I turned a template rendering system into an API interface to reuse some methods from a different script. This is not stable or good practice, a point I emphasized, but it WAS clever and I thought sharing it would be fun.







The Cheap API

Richard Still


Mature” application – a rat’s nest of legacy code written by a deranged madman**

Using Template::Toolkit


Need some of those functions in another application (script or JS)

3 years ago **

Using Template::Toolkit, you are already putting everything into a single data structure before sending it to be rendered:

$templater->process($template, $TTvars, \$output, binmode=>’:utf8′)

or $self->Probe(\@include_path, $templater->error);

Instead of sending to TT, redirect the output to JSON

if( $sending_to_api ){

use CGI;

my $q = new CGI;

use JSON;

my $utf8_encoded_json_text = encode_json $TTvars;

print $q->header(‘application/json’);

print $utf8_encoded_json_text;




Re-Use for free!

1) “Yes, I know that refactoring the original code into modules is more stable and would yield better code.”

2) “Yes, I know that ‘No Time’ is not a good excuse.”

3) “Yes, other formats for export are available, JSON just gives me the option of using this content in an AJAX interface.”

Spread the love