String::TT(3pm) | User Contributed Perl Documentation | String::TT(3pm) |
String::TT - 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 "tt" function, which takes a TT (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 "42 <-> 24".
TT provides a slightly less rich namespace for variables than perl, so we have to do some mapping. Arrays are always translated from @array to "array_a" and hashes are always translated from %hash to "hash_h". Scalars are special and retain their original name, but they also get a "scalar_s" 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 "foo_a" accessor for the "foo_a" scalar will not be generated. You will have to access it via "foo_a_s". If you delete the array, though, then "foo_a" 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 "strip" and "tt" 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 TT engine, override the "_build_tt_engine" function:
local *String::TT::_build_tt_engine = sub { return Template->new( ... ) } tt 'this uses my engine';
This module is hosted in the "jrock.us" git repository. You can view the history in your web browser at:
<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 "jrockway@cpan.org"
This module is copyright (c) 2008 Infinity Interactive. You may redistribute it under the same terms as Perl itself.
2022-06-17 | perl v5.34.0 |