NAME

Text::Templet - template processor built using Perl's eval()

SYNOPSIS

Iterating through a list

use Text::Templet;
use vars qw( $dataref $counter );
$dataref = ["Money For Nothing","Communique","Sultans Of Swing"];

Templet(<<'EOT'
Content-type: text/html

<body>
<% $counter = -1 %>
<%SONG_LIST%>
<% $counter++; return "SONG_LIST_END" if $counter >= scalar(@$dataref); '' %>
<div>
$counter: $dataref->[$counter]
</div>
<%"SONG_LIST"%><%SONG_LIST_END%>
</body>
EOT
);

Conditional inclusion

use Text::Templet;
use vars qw($super_user);
$super_user = 1;

Templet(<<'EOT'
Content-type: text/html

<body>
<% "SKIP_CP" unless $super_user %>
Admin Options: <a href="control_panel.pl">Control Panel</a>
<%SKIP_CP%>
</body>
EOT
);

Alternative inclusion

use Text::Templet;
use vars qw($super_user);
$super_user = 1;

Templet(<<'EOT'
Content-type: text/html

<body>
<% "*SKIP_CP" unless $super_user %>
Admin Options: <a href="control_panel.pl">Control Panel</a>
<%*SKIP_CP%>
No Admin options available.
<%SKIP_CP%>
</body>
EOT
);

Switch-like construct

use Text::Templet;
use vars qw($super_user);
$select = 1;

$select = 0 if ( int($select) < 0 or int($select) > 2 );  

Templet(<<'EOT'
Content-type: text/html

<body>
<% "*SEL".int($select) %>
<%*SEL0%>
Select is 0
<%SEL0%>
<%*SEL1%>
Select is 1
<%SEL1%>
<%*SEL2%>
Select is 2
<%SEL2%>
</body>
EOT
);

Calling a Perl subroutine from inside a template

use Text::Templet;

sub hello_world()
{
    print "Hello, World!";
}

Templet(<<'EOT'
Content-type: text/html

<body>
<% hello_world(); '' %>
</body>
EOT
);

Using subroutine return value as a label

use Text::Templet;

sub give_me_label()
{
    return 'L1';
}

Templet(<<'EOT'
Content-type: text/html

<body>
<% give_me_label(); %>
This text will be omitted.
<%L1%>
</body>
EOT
);

A simple form

use Text::Templet;
use CGI;
use vars qw( $title $desc );
$title = "Title here!";
$desc = "Description Here!";
$title = &CGI::escapeHTML($title||'');
$desc = &CGI::escapeHTML($desc||'');

Templet(<<'EOT'
Content-type: text/html

<body>
<form method="POST" action="submit.pl">
<input name="title" size="60" value="$title">
<textarea name="desc" rows="3" cols="60">$desc</textarea>
<input type="submit" name="submit" value="Submit">
</form>
</body>
EOT
);

Sending output to a disk file

use Text::Templet;
local *FILE;
open( FILE, '>page.html' ) or warn("Unable to open file page.html: $!"), return 1;
my $saved_stdout = select(*FILE);

Templet(<<'EOT'
<body>
Hello, World!
</body>
EOT
);

select($saved_stdout);
close FILE;

Saving output in a variable

use Text::Templet;

my $output = Templet(<<'EOT'
<body>
Hello, World!
</body>
EOT
);

print $output;

Includes

use Text::Templet;
use vars qw($title $text);
$title = 'Page Title';
$text = 'Page Body';

sub header
{
  Templet('<html><head><title>$title</title></head><body>'); 
  ''
}

sub footer
{
  Templet('</body></html>');
  ''
}


Templet(<<'EOT'
Content-type: text/html

<% header() %>
<h1>$title</h1>
<div>
$text
</div>
<% footer() %>
EOT
);

A structured application

use CGI;
use Text::Templet;
use vars qw($body_sub $title);

$Q = new CGI;

if ( $Q->param('p') eq 'page1' )
{
  $title = 'Page 1';
  $body_sub = sub
  {
    Templet('Page 1'); 
  }
}
elseif ( $Q->param('p') eq 'page2' )
{
  $title = 'Page 2';
  $body_sub = sub
  {
    Templet('Page 2'); 
  }
}
else
{
  $title = 'Default Page';
  $body_sub = sub
  {
    Templet('Default Page'); 
  }
}

Templet(<<'EOT'
Content-type: text/html

<html><head><title>$title</title></head>
<body>
<h1>$title</h1>
<div>
<% &$body_sub(); '' %>
</div>
</body></html>
EOT
);

DESCRIPTION

Text::Templet is a Perl module implementing a very efficient and fast template processor that allows you to embed Perl variables and snippets of Perl code directly into HTML, XML or any other text. Text::Templet is unique in that it employs Perl's eval() function for features that other template systems implement using regular expressions, introducing a whole new syntax, with complexity proportional to the system's sophistication. Text::Templet uses Perl syntax for all its functionality, which greatly simplifies and speeds up processing of the template.

In the examples above the template text is embedded into the Perl code, but it could just as easily be loaded from a file or a database. Text::Templet does not impose any particular application framework or CGI library or information model on you. You can pick any of the existing systems or integrate Text::Templet into your own.

When called, Templet() applies a regular expression matching text enclosed within <% %> to create a list of sections. These sections are then passed to the eval() function. Sections containing text outside <% %> ("Template text sections") are wrapped into double quotes and passed to eval() for variable expansion. In void context, the value returned by the eval() is printed to the standard output, otherwise it is appended to the return value stored in $_outt.

Sections with text inside <% %> are handled in two different ways. If the text contains only alphanumeric characters without spaces, and the first character is an asterisk, a letter or an underscore, Text::Templet recognizes the section as a "label", which is then added to the internal list of labels. Labels are used to pass template processing point to the section immediately following the label, very similar to the way labels used in many programming languages to move the execution point of a program.

If it is not a label, then it is a template code section, which is passed to eval() for execution as Perl code. The return value of a code section is then used as the name of the label to jump to, allowing you to implement loops, conditionals and any other control statements using Perl code. A warning is produced if the label with that name is not found in the template, and the text that does not represent a valid label name is discarded.

When a portion of a template is contained between two labels, named identically except the first one pre-pended with "*" (asterisk), this portion will be skipped in the normal flow of template processing, and can only be reached by returning the name of the label with the asterisk from a code section. This simplifies the syntax of conditionals, switches and other types of constructs. The following two examples are equivalent, one is written using an asterisk label and the other is not:

<% "*SKIP" unless $condition %>
Text displayed when the condition is true
<%*SKIP%>
Text displayed when the condition is false
<%SKIP%>

<% "ELSE" unless $condition %>
Text displayed when the condition is true
<%"ELSE_END"%><%ELSE%>
Text displayed when the condition is false
<%ELSE_END%>

All package variables that you plan to use in the template must be declared with use vars - code and variable names embedded into the template are evaluated in the namespace of the calling package, but are contained in the lexical scope of Templet.pm. This means that lexical variables declared with my, our or local are inaccessible from "inside" the template.

The following variable names are used internally by Text::Templet and will mask variables declared in your program, making their values inaccessible in the template: %_labels, @_tpl_parsed, $_tpl_warning, $_label_regexp, $_isect, $_nsect, $_sect_text, $_save_sig, $_outf, $_outt

EXPORTS

&Templet($)

Takes template text as the argument. In void context, prints processing result to the default output, otherwise accumulates it in internal variable $_outt and returns it to the caller. Returns an empty string if an error occurred in a code section of the template. You should check the server's error log to find out which section it is.

NOTES AND TIPS

  • Using interpolating quotes around the template text wreaks havoc as variables are interpolated before Text::Templet has a chance to look at them. This is the purpose of single quotes around EOT at the examples above - to prevent early interpolation.

  • Warning 'Use of uninitialized value in concatenation (.) or string at (eval ...) line x (#x)' indicates that a variable used in the template contains an undefined value, which may happen when you pull the data from a database and some of the fields in the database record being queried contain NULL. This issue can be resolved either on the data level, by ensuring that there are no NULL values stored in the database, or on the script level by replacing undefined values returned from the database with empty strings. The simple form example above deals with this problem by using || operator during the call to &CGI::escapeHTML to assign an empty string to the variable if it evaluates to false.

  • Label names are case sensitive, and there must be no spaces anywhere between <% and %> for it to be interpreted as a label. All labels in a template must have unique names.

  • Text::Templet is compatible with mod_perl. However, make sure that each Perl function has a unique name across all scripts on the server running mod_perl. The best way to ensure that is to put each Perl file into its own package. Reusing function names among different files will result in 'function reload' warnings and functions from wrong files being called.

  • Watch the web server's error log closely when debugging your application. Text::Templet posts a warning when there is something wrong with the template, including the line number of the beginning of the section where the error occurred.

  • Call &$_outf() from within <% %> to append something to the output: <% &$_outf("foo") %>. This function takes one argument and will either send it to the standard output or append it to $_outt depending on Templet's calling context.

  • To prevent Text::Templet from trying to use the result of the processing in the template code section as a label name, add an empty string at the end: <% print "foo"; '' %>.

  • Be careful not to create infinite loops in the template as Text::Templet does not check for them. I may come up with a version specifically for debugging templates, but it is not a priority right now.

  • Text::Templet's version number is the CVS revision of the file, which means some numbers may get skipped.

AUTHOR

Denis Petrov <denispetrov@yahoo.com>

For more examples and support, visit Text::Templet Home at http://www.denispetrov.com/magic/