views:

358

answers:

3

I have some strings that I am pulling out of a database and I would like to use Template Toolkit on them, but I can't seem to figure out how to use strings as TT input. Any tips?

Thanks!

-fREW

+7  A: 

The documentation explains:

process($template, \%vars, $output, %options)

The process() method is called to process a template. The first parameter indicates the input template as one of: a filename relative to INCLUDE_PATH, if defined; a reference to a text string containing the template text; ...

       # text reference
       $tt->process(\$text)
           || die $tt->error(), "\n"
oeuftete
Ok, I got it to work. The issue was that I was using the third param (so that I wouldn't have to output the result immediately) and forgot to make it a reference. Here's what works: $template->process(\$body_template, $template_vars, \$output);
Frew
+2  A: 

From the docs:

# text reference
$text = "[% INCLUDE header %]\nHello world!\n[% INCLUDE footer %]";
$tt->process(\$text)
    || die $tt->error(), "\n";

(Looks like I should have refreshed the page before posting.)

Mr. Muskrat
+1  A: 

You may find String::TT as a nicer alternative way of doing it. Some teasers from the pod...

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(",") %]
   }
}

and...

my $scalar = 'scalar';
my @array  = qw/array goes here/;
my %hash   = ( hashes => 'are fun' );

tt '[% scalar %] [% scalar_s %] [% array_a %] [% hash_h %]';

/I3az/

draegtun
http://search.cpan.org/perldoc?String::TT
Brad Gilbert