Use tt to interpolate lexical variables
use String::TT qw/tt strip/; sub foo { my $self = shift; return tt 'my name is [% self.name %]!'; } sub bar { my @args = @_; return strip tt q{ Args: [% args_a.join(",") %] } }
String::TT exports a \*(C`tt\*(C' function, which takes a \s-1TT\s0 (Template Toolkit) template as its argument. It uses the current lexical scope to resolve variable references. So if you say:
my $foo = 42; my $bar = 24;
tt '[% foo %] <-> [% bar %]';
the result will be \*(C`42 <-> 24\*(C'.
\s-1TT\s0 provides a slightly less rich namespace for variables than perl, so we have to do some mapping. Arrays are always translated from @array to \*(C`array_a\*(C' and hashes are always translated from %hash to \*(C`hash_h\*(C'. Scalars are special and retain their original name, but they also get a \*(C`scalar_s\*(C' alias. Here's an example:
my $scalar = 'scalar'; my @array = qw/array goes here/; my %hash = ( hashes => 'are fun' );
tt '[% scalar %] [% scalar_s %] [% array_a %] [% hash_h %]';
There is one special case, and that's when you have a scalar that is named like an existing array or hash's alias:
my $foo_a = 'foo_a'; my @foo = qw/foo array/;
tt '[% foo_a %] [% foo_a_s %]'; # foo_a is the array, foo_a_s is the scalar
In this case, the \*(C`foo_a\*(C' accessor for the \*(C`foo_a\*(C' scalar will not be generated. You will have to access it via \*(C`foo_a_s\*(C'. If you delete the array, though, then \*(C`foo_a\*(C' will refer to the scalar.
This is a very cornery case that you should never encounter unless you are weird. 99% of the time you will just use the variable name.
None by default, but \*(C`strip\*(C' and \*(C`tt\*(C' are available.
Treats $template as a Template Toolkit template, populated with variables from the current lexical scope. Removes a leading empty line and common leading spaces on each line. For example,
strip q{ This is a test. This is indented. };
Will yield the string "This is a test\n This is indented.\n".
This feature is designed to be used like:
my $data = strip tt q{ This is a [% template %]. It is easy to read. };
Instead of the ugly heredoc equivalent:
my $data = tt <<'EOTT'; This is a [% template %]. It looks like crap. EOTT
If you want to pass args to the \s-1TT\s0 engine, override the \*(C`_build_tt_engine\*(C' function:
local *String::TT::_build_tt_engine = sub { return Template->new( ... ) } tt 'this uses my engine';
This module is hosted in the \*(C`jrock.us\*(C' git repository. You can view the history in your web browser at:
http://git.jrock.us/?p=String-TT.git;a=summary <http://git.jrock.us/?p=String-TT.git;a=summary>
and you can clone the repository by running:
git clone git://git.jrock.us/String-TT
Patches welcome.
Jonathan Rockway \*(C`[email protected]\*(C'
This module is copyright (c) 2008 Infinity Interactive. You may redistribute it under the same terms as Perl itself.