NAME

CGI::FastTemplate - Perl extension for managing templates, and performing variable interpolation.

SYNOPSIS

  use CGI::FastTemplate;

  $tpl = new CGI::FastTemplate();
  $tpl = new CGI::FastTemplate("/path/to/templates");

  CGI::FastTemplate->set_root("/path/to/templates");	## all instance will use this path
  $tpl->set_root("/path/to/templates");			## this one instance will use this path

  $tpl->define(		main	=> "main.tpl",
			row	=> "table_row.tpl",
			all	=> "table_all.tpl",
		);

  $tpl->assign(	TITLE	=> "I am the title.");

  my %defaults = (	FONT	=> "<font size=+2 face=helvetica>",
			EMAIL	=> 'jmoore@sober.com',
			);	
  $tpl->assign(\%defaults);


  $tpl->parse(ROWS	=> ".row");		## the '.' appends to ROWS
  $tpl->parse(CONTENT	=> ["row", "all"]);
  $tpl->parse(CONTENT	=> "main");

  $tpl->print();		## defaults to last parsed
  $tpl->print("CONTENT");	## same as print() as "CONTENT" was last parsed

  $ref = $tpl->fetch("CONTENT");

DESCRIPTION

What is a template?

A template is a text file with variables in it. When a template is parsed, the variables are interpolated to text. (The text can be a few bytes or a few hundred kilobytes.) Here is a simple template with one variable ('$NAME'):

    Hello $NAME.  How are you?
	

 

When are templates useful?

Templates are very useful for CGI programming, because adding HTML to your perl code clutters your code and forces you to do any HTML modifications. By putting all of your HTML in separate template files, you can let a graphic or interface designer change the look of your application without having to bug you, or let them muck around in your perl code.

There are other templating modules on CPAN, what makes FastTemplate different?

Speed

FastTemplate doesn't use eval, and parses with a single regular expression. It just does simple variable interpolation (i.e. there is no logic that you can add to templates - you keep the logic in the code). That's why it's has 'Fast' in it's name!

Efficiency

FastTemplate functions accept and return references whenever possible, which saves needless copying of arguments (hashes, scalars, etc).

Flexibility

The API is robust and flexible, and allows you to build very complex HTML documents/interfaces. It is also completely written in perl and works on Unix or NT. Also, it isn't restricted to building HTML documents -- it could be used to build any ascii based document (e.g. postscript, XML, email).

The similar modules on CPAN are:

Module          Taco::Template  (KWILLIAMS/Taco-0.04.tar.gz)
Module          Text::Template  (MJD/Text-Template-0.1b.tar.gz)

What are the steps to use FastTemplate?

The main steps are:

1. define
2. assign 
3. parse
4. print

These are outlined in detail in CORE METHODS below.

CORE METHODS

define(HASH)

The method define() maps a template filename to a (usually shorter) name. e.g.

    my $tpl = new FastTemplate();
    $tpl->define(main	=> "main.tpl",
                 footer	=> "footer.tpl",
			);

This new name is the name that you will use to refer to the templates. Filenames should not appear in any place other than a define().

(Note: This is a required step! This may seem like an annoying extra step when you are dealing with a trivial example like the one above, but when you are dealing with dozens of templates, it is very handy to refer to templates with names that are indepandant of filenames.)

TIP: Since define() does not actually load the templates, it is simpler to define all the templates with one call to define().

assign(HASH)

The method assign() assigns values for variables. In order for a variable in a template to be interpolated it must be assigned. There are two forms which have some important differences. The simple form, is to accept a hash and copy all the key/value pairs into a hash in FastTemplate. There is only one hash in FastTemplate, so assigning a value for the same key will overwrite that key.

e.g.

$tpl->assign(TITLE	=> "king kong");
$tpl->assign(TITLE	=> "godzilla");    ## overwrites "king kong"

assign(HASH REF)

A much more efficient way to pass in values is to pass in a hash reference. (This is particularly nice if you get back a hash or hash reference from a database query.) Passing a hash reference doesn't copy the data, but simply keeps the reference in an array. During parsing if the value for a variable cannot be found in the main FastTemplate hash, it starts to look through the array of hash references for the value. As soon as it finds the value it stops. It is important to remember to remove hash references when they are no longer needed.

e.g.

my %foo = ("TITLE" => "king kong");
my %bar = ("TITLE" => "godzilla");

$tpl->assign(\%foo);	## TITLE resolves to "king kong"
$tpl->clear_href(1);	## remove last hash ref assignment (\%foo)
$tpl->assign(\%bar);	## TITLE resolves to "godzilla"

$tpl->clear_href();		## remove all hash ref assignments

$tpl->assign(\%foo);	## TITLE resolves to "king kong"
$tpl->assign(\%bar);	## TITLE _still_ resolves to "king kong"

parse(HASH)

The parse function is the main function in FastTemplate. It accepts a hash, where the keys are the TARGET and the values are the SOURCE templates. There are three forms the hash can be in:

$tpl->parse(MAIN => "main");		## regular

$tpl->parse(MAIN => ["table", "main"]);	## compound

$tpl->parse(MAIN => ".row");		## append

In the regular version, the template named "main" is loaded if it hasn't been already, all the variables are interpolated, and the result is then stored in FastTemplate as the value MAIN. If the variable '$MAIN' shows up in a later template, it will be interpolated to be the value of the parsed "main" template. This allows you to easily nest templates, which brings us to the compound style.

The compound style is designed to make it easier to nest templates. The following are equivalent:

    $tpl->parse(MAIN => "footer");		
    $tpl->parse(MAIN => "main");

    ## is the same as:

    $tpl->parse(MAIN => ["table", "main"]);	## this form saves function calls
						## (and makes your code cleaner)

It is important to note that when you are using the compound form, each template after the first, must contain the variable that you are parsing the results into. In the above example, 'main' must contain the variable '$MAIN', as that is where the parsed results of 'table' is stored. If 'main' does not contain the variable '$MAIN' then the parsed results of 'table' will be lost.

The append style is a bit of a kludge, but it allows you to append the parsed results to the target variable. This is most useful when building tables that have an dynamic number of rows - such as data from a database query.

print(SCALAR)

The method print() prints the contents of the named variable. If no variable is given, then it prints the last variable that was used in a call to parse which I find is a reasonable default. e.g.

$tpl->print();         ## continuing from the last example, would print the value of MAIN
$tpl->print("MAIN");   ## ditto

This method is provided for convenience. If you need to print somewhere else (e.g. socket, file handle) you would want to fetch() a reference to the data first. e.g.

my $data_ref = $tpl->fetch("MAIN");
print FILE $$data_ref;			## save to a file

OTHER METHODS

fetch(SCALAR)

Returns a scalar reference to parsed data.

$tpl->parse(CONTENT	=> "main");
my $content = $tpl->fetch("CONTENT");	

print $$content;		## print to STDOUT
print FILE $$content;	## print to filehandle or pipe

clear()

Note: All of 'clear' functions are for use under mod_perl (or anywhere where your scripts are persistant). They generally aren't needed if you are writing CGI scripts.

Clears the internal hash that stores data passed to:

$tpl->parse();

Often clear() is at the end of a mod_perl script:

$tpl->print();
$tpl->clear();

clear_parse()

See: clear()

clear_href(NUMBER)

Removes a given number of hash references from the list of hash refs that is built using:

$tpl->assign(HASH REF);

If called with no arguments, it removes all hash references from the array.

clear_define()

Clears the internal hash that stores data passed to:

$tpl->define();

Note: The hash that holds the loaded templates is not touched with this method. See: clear_tpl

clear_tpl()

Clears the internal hash that stores the contents of the templates. If you are having problems with template changes not being reflected, try adding this method to your script.

clear_all()

Cleans the module of any data, except for the ROOT directory. Equivalent to:

$tpl->clear_define();
$tpl->clear_href();
$tpl->clear_tpl();
$tpl->clear_parse();

Variables

A variable is defined as:

$[A-Z0-9][A-Z0-9_]+

This means, that a variable must begin with a dollar sign '$'. The second character must be an uppercase letter or digit 'A-Z0-9'. Remaining characters can include an underscore.

For example, the following are valid variables:

$FOO
$F123F
$TOP_OF_PAGE

Variable Interpolation (Template Parsing)

When the a template is being scanned for variables, pattern matching is greedy. (For more info on "greediness" of regexps see perlre.) This is important, because if there are valid variable characters after your variable, FastTemplate will consider them to be part of the variable. The only way that you can indicate the end of your variable name is to have a character that is not an uppercase letter, digit or underscore. ['A-Z0-9_']

If a variable cannot be resolved to anything, it is converted to an empty string [""].

Some examples will make this clearer.

    Assume:

    $FOO = "foo";
    $BAR = "bar";
    $ONE = "1";
    $TWO = "2";	
    $UND = "_";
	
    Variable	Interpolated/Parsed
    ------------------------------------------------
    $FOO		foo	
    $FOO-$BAR	foo-bar
    $ONE_$TWO	_2			## $ONE_ is undefined!	
    $ONE$UND$TWO	1_2
    $$FOO		$foo
    $25,000		$25,000

FULL EXAMPLE

This example will build an HTML page that will consist of a table. The table will have 3 numbered rows. The first step is to decide what templates we need. In order to make it easy for the table to change to a different number of rows, we will have a template for the rows of the table, another for the table, and a third for the head/body part of the HTML page.

Below are the templates. (Pretend each one is in a separate file.)

 <!-- NAME: main.tpl -->
 <html>
 <head><title>$TITLE</title>
 </head>
 <body>
 $MAIN
 </body>
 </html>
 <!-- END: main.tpl -->


 <!-- NAME: table.tpl -->
 <table>
 $ROWS
 </table>
 <!-- END: table.tpl -->


 <!-- NAME: row.tpl -->
 <tr>
 <td>$NUMBER</td>
 <td>$BIG_NUMBER</td>
 </tr>
 <!-- END: row.tpl -->

Now we can start coding...

 ## START ##

  use CGI::FastTemplate;
  my $tpl = new CGI::FastTemplate("/path/to/template/files");
 
  $tpl->define(	main	=> "main.tpl",
		table	=> "table.tpl",
		row	=> "row.tpl",
		);

  $tpl->assign(	TITLE	=> "FastTemplate Test");

  for $n (1..3) {
	$tpl->assign(	NUMBER		=> $n,	
			BIG_NUMBER	=> $n*10);
	$tpl->parse(ROWS	=> ".row"); 
  }

  $tpl->parse(MAIN	=> ["table", "main"]); 
  $tpl->print();

  ## END ##
 
  When run it returns:

  <!-- NAME: main.tpl -->
  <html>
  <head><title>FastTemplate Test</title>
  </head>
  <body>
  <!-- NAME: table.tpl -->
  <table>
  <!-- NAME: row.tpl -->
  <tr>
  <td>1</td>
  <td>10</td>
  </tr>
  <!-- END: row.tpl -->
  <!-- NAME: row.tpl -->
  <tr>
  <td>2</td>
  <td>20</td>
  </tr>
  <!-- END: row.tpl -->
  <!-- NAME: row.tpl -->
  <tr>
  <td>3</td>
  <td>30</td>
  </tr>
  <!-- END: row.tpl -->
  
  </table>
  <!-- END: table.tpl -->

  </body>
  </html>
  <!-- END: main.tpl -->

If you're thinking you could have done the same thing in a few lines of plain perl, well yes you probably could. But, how would a graphic designer tweak the resulting HTML? How would you have a designer editing the HTML while you're editing another part of the code? How would you save the output to a file, or pipe it to another application (e.g. sendmail)? How would you make your application multi-lingual? How would you build an application that has options for high graphics, or text-only? FastTemplate really starts to shine when you are building mid to large scale web applications, simply because it begins to separate the application's generic logic from the specific implementation.

AUTHOR

Jason Moore <jmoore@sober.com>

SEE ALSO

mod_perl(1).