Because CPAN Needs More Templating Modules

Why learn a whole new language for templating when you already know a perfectly good one? This isn't the first module that allows you to embed Perl in your templates, but it's yet another one.

use Types::Standard -types;
use Template::Compiled;
my $template = Template::Compiled->new(
signature => [
name => Str,
age => Int->plus_coercions(Num, sub { int $_ } ),
],
template => '<p>Hi <?= $name ?>. You are <?= $age ?> years old.</p>',
escape => 'html',
);
# The number will be rounded.
# The ampersand will be escaped properly.
#
print $template->( name => 'Alice & Bob', age => 45.1 );
view raw example.pl hosted with ❤ by GitHub

Template::Compiled on MetaCPAN.

2 Comments

I like it since I'm a fan of strongly typed interfaces for the template. I'd love to take it even further, like the template is a subclass of Template::Compiled::Class and the class attributes and methods are exposed to the template like

package MyApp::Template::User;

use Moo;
use Types::Standard -types;
extends 'Template::Compiled::Class';

has [qw/name age/] => (is=>'ro', required=>1, isa=>Str);

sub days_since_birth { DateTime->now - $self->age }

sub template {
"Hi its been days
since you were born!";
}

1;

Sadly I think BPO ate some significant parts of your template in the comment.

Leave a comment

Sign in to comment.

About Toby Inkster

user-pic I'm tobyink on CPAN, IRC and PerlMonks.