[Templates] TT for error messages

Brad Bowman list@bereft.net
Thu, 19 Jul 2007 13:39:01 +1000


Hello,

I'm considering using TT2 to generate error messages from a
string template.
Does anyone have recommendations on how to do it?
Can I avoid reparsing the message templates somehow?

Here's a sketch:

#perl -w
use Template;
use String::Escape qw(printable);

my $tt = Template->new(
             INTERPOLATE     => 1,
             START_TAG       => quotemeta('<<'),
             END_TAG         => quotemeta('>>'),
         );

$Template::Stash::SCALAR_OPS->{ quote } = sub {
     my $item = shift;
     return '"' . printable($item) . '"';
};

# msg_template would come from a database
my $msg_template =
    'Line $lineno too short, length <<line.length || 0>>, line.quote';
my $context = { line => "a b c\cM", lineno => 123 };

my $message;
$tt->process(\$msg_template, $context, \$message)
     or do {
         warn "Message template error: ".$tt->error;
         $message = $msg_template;
     };

print $message, "\n";

__END__

Brad

-- 
... Within the tedious talk of old folks are their meritorious deeds.
                                -- Hagakure http://bereft.net/hagakure/