4

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

Frew Schmidt
  • 9,364
  • 16
  • 64
  • 86

3 Answers3

11

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
  • 2,628
  • 1
  • 24
  • 33
  • 1
    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 Schmidt Nov 24 '08 at 18:27
4

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
  • 22,772
  • 3
  • 20
  • 21
2

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 %]';
AndyG
  • 39,700
  • 8
  • 109
  • 143
draegtun
  • 22,441
  • 5
  • 48
  • 71