Tuesday, December 25, 2007

Template Toolkit

The Template Toolkit is a collection of Perl modules which implement a fast, flexible, powerful and extensible template processing system. It is most often used for generating dynamic web content, although it can be used equally well for processing any kind of text documents......

To get into Intro: Template Toolkit

To Start with template toolkit:
cpan> install Template

Instructions :

tt- template toolkit

1) Don't set "INTERPOLATE" constructor, while creating template new object.

2) All directives in TT should be in caps

eg:
[% BLOCK %]
------
------
[% END %]

3) To process a tt file include the filename in '<file_name.tt>'
[% PROCESS 'file.tt' %]

4) To process a block call it by block name
[%PROCESS %]

5) We can pass scalar, hash and array only through CGI to tt. :-) (Not to pass code reference or objects).

5) use SET to declare a variable in tt.

[% SET foo = 100 %]
[% foo %]

6) COMMENTS :
To give multi line comments, give # without giving space after [%

[%# sdjfkdnf
sdfkldjfkj
%]

To give a single comment
[% SET foo = 10 #Declaring the variable
%]

7)Ternary Operator allowed.

8) Use 'IN' instead of '=', while using for each syntax

9) Use 'FILTER' instead of '|'

Example Program with 'foo.tt' file:
--------------------------------
1. Create a 'foo.tt' file.

Dear [% name %],

It has come to our attention that your account is in
arrears to the sum of [% debt %].

Please settle your account before [% deadline %] or we
will be forced to revoke your Licence to Thrill.

The Management.

2. Paste the above text. Save & close 'foo.tt' file.
3. create a 'template_toolkit.pl' file from the same directory.
#!/usr/local/bin/perl
use strict;
use warnings;
use Template;

# To get more details
#http://template-toolkit.org/

my $tt = Template->new({
INCLUDE_PATH => '',
}) || die "$Template::ERROR\n";

my $vars = { name => 'Operative',
debt => '1 billion dollars',
deadline => 'next month',
};
$tt->process('foo.tt', $vars) || die $tt->error();

4. Paste the above code. Save & close 'template_toolkit.pl' file.
5. Run the Perl file. (perl template_toolkit.pl).

Output : Name substituted by 'Operative' and follows....

No comments :

// Below script tag for SyntaxHighLighter