FastTemplate Class Reference

FastTemplate.php - A PHP4 class for template processing and performing variable interpolation. More...

List of all members.

Public property methods

getDynamic ($aToken= '')
Get a list of dynamic blocks.
setDynamic ($aToken, $aTemplate= '')
Setup a dynamic template.
getError()
Get the most recent error description.
getRoot()
Get the current value of the Root property.
setRoot ($aDirectory, $aPathDelimiter= '/')
Set the value of the Root property.
getStrict()
Get the current value of the Strict property.
setStrict ($beStrict=TRUE)
Set the value of the Strict property.
setTemplate ($aToken, $aFile= '')
Map a template's filename to a (usually shorter) symbolic name.
getTokens ($aToken= '')
Get a list of variable tokens used in the given template.
getVariable ($aToken= '')
Get the value of a defined variable token.
setVariable ($aToken, $aValue= '')
Assign values for variable tokens.
getVerbose()
Get the current value of the Verbose property.
setVerbose ($doPrint=TRUE)
Get the current value of the Verbose property.

Public Member Functions

FastTemplate ($aDirectory= '', $aPathDelimiter= '/')
Constructor for class FastTemplate.
API methods
clear()
Clean the class instance of any data, except for the Root property.
clearDynamic ($aToken)
Strip a dynamic block from a template.
clearError()
Clear the current error description.
clearLoaded ($aToken= '')
Clear the internal list that stores the contents of the templates.
clearTemplate ($aToken= '')
Clear the internal mapping-list of symbolic template names to file names as defined with setTemplate().
clearVariable ($aToken= '')
Clear variable tokens set by setVariable().
fetch ($aToken= '', $stripComments=TRUE)
Get the raw data from a parsed template.
parse ($aTargetToken, $aSourceTemplate)
Perform the {TOKEN} to 'value' conversion within a template.
write ($aToken= '', $stripComments=TRUE)
Print the contents of the specified $aToken.

Detailed Description

FastTemplate.php - A PHP4 class for template processing and performing variable interpolation.

Synopsis

    require_once('FastTemplate.php');   // make the class available
     
    $tpl = new FastTemplate();
    $tpl->setTemplate(array(
        'main' => 'main.tpl',
        'row'  => 'table_row.tpl',
        'all'  => 'table_all.tpl'));
     
    $tpl->setVariable('TITLE', 'I am the title.');
    $defaults = array(
        'HOME'  => '<a href="/index.html">home page</a>',
        'EMAIL' => 'user&#40;host.example.com');
    $tpl->setVariable($defaults);
     
    $tpl->parse('ROWS', '.row'); // the '.' appends to ROWS
    $tpl->parse('CONTENT', array('row', 'all'));
    $tpl->parse('CONTENT', 'main');
     
    $tpl->write('CONTENT');
     
    // or: 
    $raw = $tpl->fetch('CONTENT', FALSE);
    print("$raw\n");
 

Overview

What is a template?

A template is a text file with variables (special tokens) in it. When a template is parsed, the variables are interpolated to text. which 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 X/HTML to your PHP code clutters your code and forces you to do any X/HTML modifications. By putting all of your X/HTML in seperate 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 PHP code.

Why use FastTemplate?

Speed

FastTemplate 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 while preserving both the document's structure and design in your template.

Flexibility

The API is robust and flexible, and allows for building very complex X/HTML documents/interfaces. It is also completely written in PHP and (should) work on any* NIX like plattform. Also, it isn't restricted to building HTML documents -- it could be used to build any ASCII based document (postscript, XML, email - anything).

What are the steps to use FastTemplate?

The main steps usually are:

For more details see the respective method's documentation and the example below.

Variable tokens

A variable token is a special string of characters placed in your template files. It is defined as:

    {[A-Z][A-Z_0-9]*}
 

This means, that a variable token must begin with a curly brace {. The second character must be an ASCII uppercase letter and the optional remaining characters may be ASCII uppercase letters, digits or underscores. The variable token is terminated by a closing curly brace }. - For example, the following are valid variable tokens:

    {FOO}
    {F123F}
    {TOP_OF_PAGE}
 

The following are not accepted as valid variable tokens and therefore will be left untouched in the parsed output:

    {f00}           // second char not uppercase
    {1ST_VAR}       // second char no letter
    {Top_of_page}   // lowercase letters are not allowed
 

The definition of a dynamic token (see setDynamic() and the example below) is similar, except that here lowercase characters are allowed as well and the curly braces are not:

    [A-Za-z][A-Za-z0-9_]*
 

Hint: Although it's not exactly required, at least it's recommended to always use lowercase letters for the strings used by your PHP code as symbolic template names and dynamic token names. This avoids possible problems when using linked, nested or dynamic templates as such lowercase strings can never conflict with the uppercase strings used for the other variable tokens within the template files.

Variable Interpolation (Template Parsing)

If a valid variable token cannot be resolved to anything, a warning is printed to STDOUT. (See setStrict() and setVerbose() for additional info.) Some examples might make this clearer; assume:

    $FOO = 'foo';
    $BAR = 'bar';
    $ONE = '1';
    $TWO = '2';    
    $UND = '_';
  
    Template token    Interpolated/Parsed value
    ------------------------------------------------------
    {FOO}             foo    
    {FOO}-{BAR}       foo-bar
    {ONE_TWO}         {ONE_TWO} // {ONE_TWO} is undefined!    
    {ONE}{UND}{TWO}   1_2
    ${FOO}            $foo
    $25,000           $25,000
    {foo}             {foo}     // left untouched as is,
                                // it's not a valid token.
 

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. We will use lowercase letters here to specify symbolic template names and uppercase letters to specify variable tokens.

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

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

 

    <!-- NAME: table.tpl -->
    <table summary="this is the data">
        {ROWS}
    </table>
    <!-- END: table.tpl -->
 

 

    <!-- NAME: main.tpl -->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <!-- {TITLE}: -->
        <title>{TITLE}</title>
    </head>
    <body>
        <!-- start contents -->
        {MAIN}
        <!-- end contents -->
    </body>
    </html>
    <!-- END: main.tpl -->
 

Now we can start coding...

    <?php
    error_reporting(E_ALL);
     
    // make class definition available:
    require_once(dirname(__FILE__) . '/FastTemplate.php');
     
    $DYNAMIC = FALSE;
     
    // instanciate new object:
    $tpl = new FastTemplate();
     
    // output all errors/warnings:
    $tpl->setVerbose();
     
    // create token -> filename mapping
    $templates = ($DYNAMIC) 
        ? array(
            'main'  => 'main.tpl',
            'table' => 'dynamic.tpl')
        : array(
            'main'  => 'main.tpl',
            'table' => 'table.tpl',
            'row'   => 'row.tpl');
     
    // setup used templates:
    $tpl->setTemplate($templates);
    if ($DYNAMIC) {
        $tpl->setDynamic('row', 'table');
    } // if
     
    // setup a variable/token
    $tpl->setVariable('TITLE', 'FastTemplate Test');
     
    // fill up a few table rows
    for ($n = 1; 4 > $n; ++$n) {
        $tpl->setVariable(array(
            'NUMBER' => $n,
            'BIG_NUMBER' => $n*  10));
        $tpl->parse('ROWS', '.row');
    } // for
    // parse the page:
    $tpl->parse('MAIN', array('table', 'main'));
     
    // print out the resulting data:
    header('Content-type: text/html');
    $tpl->write();      // actually using 'MAIN'
     
    // done ...
    $tpl->clear();
    exit(0);
    ?>
 

When run it returns:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>FastTemplate Test</title>
    </head>
    <body>
    <table summary="this is the data">
    <tr><td>1</td>
    <td>10</td></tr>
    <tr><td>2</td>
    <td>20</td></tr>
    <tr><td>3</td>
    <td>30</td></tr>
     
    </table>
    </body>
    </html>
 

Now we're going to use another feature: dynamic templates (see the setDynamic() method for more information). We need another template file which kind of combines the row.tpl and table.tpl files above:

    <!-- NAME: dynamic.tpl -->
    <table summary="this is the data">
        <!-- BEGIN DYNAMIC BLOCK: row -->
    <tr><td>{NUMBER}</td><td>{BIG_NUMBER}</td></tr>
        <!-- END DYNAMIC BLOCK: row -->
    </table>
    <!-- END: dynamic.tpl -->
 

In the test script we change one variable $DYNAMIC = TRUE which slightly modifies the program's logic and run it again. The result is ... surprise, surprise ...

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
     
    <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>FastTemplate Test</title>
    </head>
    <body>
    <table summary="this is the data">
    <tr><td>1</td><td>10</td></tr>
    <tr><td>2</td><td>20</td></tr>
    <tr><td>3</td><td>30</td></tr>
    </table>
    </body>
    </html>
 

As you can see, the only difference is the format in which the table rows are printed and this is caused directly by the slightly varying format used in the row.tpl and dynamic.tpl template files.

As a sidenote: Whenever you need dynamic contents you should use the the setDynamic() method. It not only uses less memory than the linked templates variant but is faster as well.

If you're thinking now you could have done the same thing in a few lines of plain PHP, well, yes, you probably could. But, how would a graphic designer put CSS into the the resulting HTML? How would you have a designer editing the HTML/CSS while you're editing another part of the code? How would you save the output to a file, or pipe it to another application? 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 seperate the application's generic logic from the specific representation.

Credits

This class was initially a rewrite of the class.FastTemplate.php3 file available at www.thewebmasters.net/php/FastTemplate.phtml. I've made the class a little more object-oriented, providing GETter/SETter methods for all public properties, changed a couple of method and argument names, added a few methods, improved the encapsulation of the private members (as far as PHP4 allows), very much reduced memory usage and included the class documentation while updating/enhancing it to match the current development state.

Please note: While the functionality of the old class was preserved (and even enhanced) the API has changed quite a lot. I felt this neccessary to make it more consistent and clearer (actually, no byte of the original code was left untouched). To assist the process of upgrading I've marked all new methods with a 2005-01-01 date tag and included a comment whereever a method was renamed, like this:

This replaces the xxx_yyy() method of the old class.

In case you find any problems please don't bother the original authors with bugs I may have introduced.

 Copyright (C) 2004-2005 DFG/M.Watermann, D-10247 Berlin, FRG
        All rights reserved
    EMail : <matthias@OLN.ComLink.APC.org>
 
Author:
Original Perl module CGI::FastTemplate 1998 by Jason Moore jmoore(at)sober.com

PHP3 port 1999 by CDI cdi(at)thewebmasters.net

PHP4 rewrite 2004/2005 by Matthias Watermann

Version:
Id
FastTemplate.php,v 1.5 2005/08/10 09:29:47 matthias Exp

Definition at line 417 of file FastTemplate.php.


Member Function Documentation

FastTemplate::FastTemplate ( $ aDirectory = '',
$ aPathDelimiter = '/'
)

Constructor for class FastTemplate.

The Strict property of the created object is initally set TRUE and the Verbose property is FALSE. The Root property is set to the directory where this class file lives unless the optional $aDirectory argument is used to set another directory.

The second optional argument is needed only for those who are still forced to suffer WinDOS environments. Everyone else (i.e.* NIX, Linux, Mac, Solaris etc.) may safely ignore it.

Parameters:
$aDirectory String The filesystem path/name of the directory where the template files live; if unset or empty the directory of this PHP file is used instead.
$aPathDelimiter Character The character used as path delimiter by the filesystem; usually '/' (i.e. chr(47)), but '\' (i.e. chr(92)) on WinDOS systems.
Returns:
FastTemplate The new class instance.
See also:
setRoot($aDirectory)

setStrict($beStrict)

setVerbose($doPrint)

Definition at line 453 of file FastTemplate.php.

References setRoot().

FastTemplate::getDynamic ( $ aToken = '' )

Get a list of dynamic blocks.

This method is more or less an informational convenience function which you won't usually need or call. It's meant to support you debugging your templates and application's code.

There are three ways to call this method:

$result = $tpl->getDynamic();
If the $aToken argument is unset or empty the $result will be either FALSE (if there are no dynamic templates defined with setDynamic()), or an array of all dynamic blocks read from the defined dynamic templates during parse().
$result = $tpl->getDynamic('name');
Here $result will be either FALSE (if there is no matching dynamic block defined with setDynamic()), or a string holding the dynamic block named 'var'.
$result = $tpl->getDynamic(array('for', 'bar'));
Passing an array of dynamic block names will return either FALSE (if there are no matching dynamic blocks defined with setDynamic()), or an array of the named dynamic blocks as read during parse().

Please note that this method does not return the contents of a dynamic template file but the named dynamic block(s) living inside a template file. With the dynamic template file from the example above

    <table summary="this is the data">
        <!-- BEGIN DYNAMIC BLOCK: row -->
    <tr><td>{NUMBER}</td><td>{BIG_NUMBER}</td></tr>
        <!-- END DYNAMIC BLOCK: row -->
    </table>
 

the call $tpl->getDynamic('row') would return the string

 <tr><td>{NUMBER}</td><td>{BIG_NUMBER}</td></tr>
 

Since the templates are not loaded into memory when they're defined (with setTemplate()) but only when they are actually used (by parse()) the method's result will be FALSE in either case if it's called before parse().

Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
Returns:
Mixed Either FALSE, a string or an array of strings (see explaination above).
See also:
setDynamic($aToken, $aTemplate)

setTemplate($aToken, $aFile)

parse($aTargetToken, $aSourceTemplate)

Since:
created 2005-01-01

Definition at line 728 of file FastTemplate.php.

FastTemplate::setDynamic ( $ aToken,
$ aTemplate = ''
)

Setup a dynamic template.

A dynamic block lives inside another template file. It will be stripped from $aTemplate when parsed and replaced with the given {$aToken}.

You can define dynamic content within a static template. Here's an example of setDynamic():

    $tpl = new FastTemplate();
    $tpl->setTemplate(array('main' => 'main.tpl',
        'table' => 'dynamic.tpl'));
    $tpl->setDynamic('row', 'table');
 

This tells FastTemplate that buried in the 'table' template is a dynamic block, named 'row'. - Here's how a dynamic block appears within a template file:

    <!-- NAME: dynamic.tpl -->
    <table summary="the numbers list">
    <tr>
    <th>col one</th><th>col two</th>
    </tr>
    <!-- BEGIN DYNAMIC BLOCK: row -->
    <tr>
    <td>{NUMBER}</td>
    <td>{BIG_NUMBER}</td>
    </tr>
    <!-- END DYNAMIC BLOCK: row -->
    </table>
    <!-- END: dynamic.tpl -->
 

The syntax of the BEGIN and END comments needs to be in the format shown:
<!-- BEGIN DYNAMIC BLOCK: token_name -->
and
<!-- END DYNAMIC BLOCK: token_name -->
However, you're free to place whitespace inside the comment if you should feel the need, e.g.

    <!--
        BEGIN DYNAMIC BLOCK:
            token_name
    -->
 

Now when the parse() method gets called, it will spot the dynamic block, strip it out, and use it exactly as if you had defined it as a stand-alone template with setTemplate(). No additional work is required on your part to make it work - just define it, and FastTemplate will do the remaining work.

There are a few rules when using dynamic blocks. For token_name all alphanumeric characters are allowed. Dynamic blocks must not be nested inside other dynamic blocks - strange things will occur. You can have more than one nested block of code in a page but, of course, no two blocks can share the same defined token_name.

If you define a dynamic block and FastTemplate fails to find it, no errors will be generated, just unexpected output (the dynamic data will not be appended to the returned data). Since valid BEGIN / END comments are stripped out of the parsed results, if you ever see your BEGIN or END comment in the parsed output, that means FastTemplate failed to find that dynamic block.

For allowed characters in $aToken see the examples above. If $aToken is invalid or the associated $aTemplate is empty the pair is ignored.

This replaces the define_dynamic() method of the old class.
Parameters:
$aToken Mixed The name of the dynamic block name used within the given $aTemplate, or an array of name/template pairs.
$aTemplate String The symbolic name of the template file containing the specified $aToken (string); ignored if $aToken is an array.
See also:
clearDynamic($aToken)

getDynamic($aToken)

setTemplate($aToken, $aFile)

setVariable($aToken, $aValue)

Definition at line 865 of file FastTemplate.php.

FastTemplate::getError ( )

Get the most recent error description.

Returns:
String The description of the last error occured.
See also:
setStrict($beStrict)

setVerbose($doPrint)

clearError()

Since:
created 2005-01-01

Definition at line 898 of file FastTemplate.php.

FastTemplate::getRoot ( )

Get the current value of the Root property.

Returns:
String The directory where all template files are expected.
See also:
setRoot($aDirectory)

Definition at line 910 of file FastTemplate.php.

FastTemplate::setRoot ( $ aDirectory,
$ aPathDelimiter = '/'
)

Set the value of the Root property.

All templates will be loaded from this "root" directory. This property can be changed in mid-process by re-calling this method with a new value.

The second optional argument is needed only for those who are still forced to suffer WinDOS environments. Everyone else (i.e.* NIX, Linux, Solaris, Mac etc.) may safely ignore it.

This replaces the set_root() method of the old class.
Parameters:
$aDirectory String The filesystem path/name of the directory where the template files live; if unset or empty the directory of this PHP file is used instead.
$aPathDelimiter Character The character used as path delimiter by the filesystem; usually '/' (i.e. chr(47)), but '\' (i.e. chr(92)) on WinDOS systems.
Returns:
Boolean FALSE if the given $aDirectory is not a directory, or TRUE otherwise.
See also:
getError()

setTemplate($aToken, $aFile)

Definition at line 945 of file FastTemplate.php.

Referenced by FastTemplate().

FastTemplate::getStrict ( )

Get the current value of the Strict property.

Returns:
Boolean Either TRUE or FALSE.
See also:
setStrict($beStrict)
Since:
created 2005-01-01

Definition at line 968 of file FastTemplate.php.

FastTemplate::setStrict ( $ beStrict = TRUE )

Set the value of the Strict property.

This method sets the way to handle undefined variable references found in templates. If this property is on (which is the default) all variables found during template parsing that are unresolved have a warning printed to STDOUT (at least if the Verbose property is TRUE as well):

    [FastTemplate] Warning: no value found for variable: SOME_VAR
 

Also, the variables will be left in the output document. This was done for two reasons: to allow for parsing to be done in stages (i.e. multiple passes), and to make it easier to identify undefined variables since they appear in the parsed output. If you want to replace unknown variables by an empty string, just set this property to FALSE.

This replaces the strict()/no_strict() methods of the old class.
Parameters:
$beStrict Boolean The new template checking mode (see above).
See also:
getStrict()

setVerbose($doPrint)

Definition at line 1002 of file FastTemplate.php.

FastTemplate::setTemplate ( $ aToken,
$ aFile = ''
)

Map a template's filename to a (usually shorter) symbolic name.

The new symbolic names defined here are the names that you will use to refer to the template files. - There are two ways to call this method:

$tpl->setTemplate('main', 'main.tpl');
If two strings are given the first one defines the symbolic name which will be used with other methods and the second string specifies the filename of that template.
$tpl->setTemplate(array( 'main' => 'main.tpl', 'table' => 'table.tpl', 'row' => 'row.tpl'));
Passing an array will ignore the second ($aFile) argument. The array is expected to consist of pairs of strings where each key defines a symbolic name and each value the corresponding filename.

All filenames must be relative to the Root property (defined with the setRoot() method) and they are tested: If a template file is not readable an error message is written (see setVerbose()) and the template is ignored (i.e. not added to the internal template list).

Note: This is a required step! While this may seem like an annoying extra step when dealing with a trivial example, when you are dealing with dozens of templates, it is very handy to refer to templates with symbolic names that are independant of filenames. And since this method does not actually load the template files, it's faster and more legible to define all the templates with just one call to this method. Filenames should not appear in any place other than a setTemplate() method call.

This replaces the define() method of the old class.
Parameters:
$aToken Mixed Either a string providing a symbolic token/name, or an array of token->filename pairs.
$aFile String If the given $aToken is a string (i.e. a symbolic template name) this is the template's filename, otherwise (i.e. $aToken is an array) this argument is ignored.
See also:
getTemplate($aToken)

clearTemplate($aToken)

setRoot($aDirectory)

getError()

Definition at line 1163 of file FastTemplate.php.

FastTemplate::getTokens ( $ aToken = '' )

Get a list of variable tokens used in the given template.

This method is more or less an informational convenience function which you won't usually need or call. It's meant to support you debugging your templates and application's code.

There are three ways to call this method:

$result = $tpl->getTokens();
If the $aToken argument is unset or empty the $result will be either FALSE (if no templates have been defined with setTemplate), or a string holding all variable tokens found in any template (be it static or dynamic).
$result = $tpl->getTokens('main');
Passing a symbolic template name (i.e. a string) will return either FALSE (if the specified $aToken was not defined with setTemplate), or a string holding the variable tokens found in the given template.
$result = $tpl->getTokens(array('main', 'table'));
When an array of symbolic template names is passed, the $result will be either FALSE (if no name has been defined with setTemplate), or a string holding all variable tokens found in any of the given templates.

Please note that there's no corresponding SETter method (e.g. 'setToken()'). Instead the values of this property are defined indirectly (by setTemplate() and parse()).

Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
Returns:
Mixed Either FALSE or a string holding a space-delimited list of variable tokens (see explaination above).
See also:
setTemplate($aToken, $aFile)

parse($aTargetToken, $aSourceTemplate)

Since:
created 2005-01-01

Definition at line 1237 of file FastTemplate.php.

FastTemplate::getVariable ( $ aToken = '' )

Get the value of a defined variable token.

This method is more or less an informational convenience function which you won't usually need or call. It's meant to support you debugging your templates and application's code. Additionally it allows you to easily pass variables around within your application's method by using this class to handle kind of "globalization" of the variables. For example:

    $tpl->setVariable(array('TITLE' => $title,
        'BGCOLOUR' => $bgColour,
        'TEXT' => $textColour ));
     
    // sometime later ...
     
    $bgColour = $tpl->getVariable('BGCOLOUR');
 

There are three ways to call this method:

$result = $tpl->getVariable();
With an empty or unset $aToken argument the $result will be either FALSE (if no variable token was defined with setVariable()), or an array of strings (indexed by the variable token names)with all known variable values.
$result = $tpl->getVariable('TITLE');
Passing a string with a variable token will return either FALSE (if the specified variable token was defined with setVariable()), or an string holding the variable token's current value.
$result = $tpl->getVariable(array('TITLE', 'MAIN'));
If an array of variable tokens is passed to this method the $result will be either FALSE (if none of the given variable tokens was defined with setVariable()), or an array of strings (indexed by the variable token names).

Please note that the returned string (or array of strings respectively) can grow quite large depending on the parsing state when this method is called.

This replaces the get_assigned() method of the old class.
Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
Returns:
Mixed Either FALSE, a string or an array of strings (see explaination above).
See also:
setVariable($aToken, $aValue)

parse($aTargetToken, $aSourceTemplate)

Definition at line 1355 of file FastTemplate.php.

FastTemplate::setVariable ( $ aToken,
$ aValue = ''
)

Assign values for variable tokens.

In order for a variable token in a template to be interpolated it must be assigned. - There are two ways to use this method:

$tpl->setVariable('VAR1', 'the value');
Here the string 'VAR1' names a variable token (to be used within a template) which will get replaced by the string 'the value'.
$tpl->setVariable(array('VAR2' => 'the value'));
In this form the optional $aValue is ignored but the $aToken argument is an array with possibly multiple records/rows each of which representing a variable name and its respective value.

Please note that assigning different values to the same variable token will overwrite each other; in other words: the last assignment wins. - While empty values are allowed empty variable tokens are not.

For allowed characters in $aToken see the examples above.

This replaces the assign() method of the old class.
Parameters:
$aToken Mixed Either a string naming a variable, or an array of key-value-pairs.
$aValue String If the given $aToken is a string (i.e. a variable name) this is the variable's value, otherwise (i.e. $aToken is an array) this argument is ignored.
See also:
getVariable($aToken)

clearVariable($aToken)

Definition at line 1430 of file FastTemplate.php.

FastTemplate::getVerbose ( )

Get the current value of the Verbose property.

Returns:
Boolean Either TRUE or FALSE.
See also:
setVerbose($doPrint)

getError()

Since:
created 2005-01-01

Definition at line 1453 of file FastTemplate.php.

FastTemplate::setVerbose ( $ doPrint = TRUE )

Get the current value of the Verbose property.

Errors/warnings are emitted by various SETter methods (if invalid arguments are passed) and during the parse() process (if unrecognized variable tokens are found and the Strict property is set TRUE). This property determines whether errors and warnings are actually written to STDOUT or not.

Please note that error messages can be retrieved programmatically by the getError() method even if this property is switched off.

Parameters:
$doPrint Boolean If TRUE (or unset) both errors and warnings will be written to STDOUT, if FALSE they're not.
See also:
setStrict($beStrict)

getVerbose()

getError()

Since:
created 2005-01-01

Definition at line 1482 of file FastTemplate.php.

FastTemplate::clear ( )

Clean the class instance of any data, except for the Root property.

Calling this method is identical to the following sequence:

    $tpl->clearLoaded();
    $tpl->clearTemplate();
    $tpl->clearVariable();
 
This replaces the clear_all() method of the old class.
See also:
clearLoaded($aToken)

clearTemplate($aToken)

clearVariable($aToken)

Definition at line 1514 of file FastTemplate.php.

References clearLoaded(), clearTemplate(), and clearVariable().

FastTemplate::clearDynamic ( $ aToken )

Strip a dynamic block from a template.

This method removes the dynamic block definition from its parent template provided that it hasn't already been parsed. E.g.

    $tpl->clearDynamic('row');
 

would completely strip all of the unparsed dynamic blocks named 'row' from the parent template.
There are three ways to call this method:

$tpl->clearDynamic();
If the $aToken argument is missing (or empty) then all unparsed dynamic blocks defined with setDynamic() are removed from memory.
$tpl->clearDynamic('name');
If the specified $aToken is a symbolic template name (i.e. a string) defined with setDynamic() that unparsed dynamic block is removed.
$tpl->clearDynamic(array('foo', 'bar'));
Passing an array of dynamic block names defined with setDynamic() will remove all unparsed dynamic blocks named by that array.

Note that this method does not clear any dynamic contents that's already parsed. To do that you may call the clearVariable($aToken) method. This method won't do a thing if the template has already been parsed, because the required BEGIN and END comments have been removed through the parsing. However, presuming you've called something like $tpl->parse('ROWS', '.row') as in the example above you could call $tpl->clearVariable('row') to clear the unparsed dynamic block and $tpl->clearVariable('ROWS') to clear the parsed data.

The method works well when you are accessing a database, and your row may or may not return anything to print to the template. If your database query doesn't return anything, you can strip out the rows you've set up for the results.

This replaces the clear_dynamic() method of the old class.
Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
See also:
getDynamic($aToken)

setDynamic($aToken, $aTemplate)

clearLoaded($aToken)

clearVariable($aToken)

Definition at line 1593 of file FastTemplate.php.

FastTemplate::clearError ( )

Clear the current error description.

See also:
setStrict($beStrict)

setVerbose($doPrint)

getError()

Since:
created 2005-01-01

Definition at line 1627 of file FastTemplate.php.

FastTemplate::clearLoaded ( $ aToken = '' )

Clear the internal list that stores the contents of the templates.

There are three ways to call this method:

$tpl->clearLoaded();
If the $aToken argument is missing (or empty) then all parsed templates (both dynamic and static ones) are removed from memory.
$tpl->clearLoaded('name');
If the specified $aToken is a symbolic template name (i.e. a string) the named parsed template is removed.
$tpl->clearLoaded(array('foo', 'bar'));
Passing an array of symbolic template names will remove the parsed templates named by that array.

If there are problems with template changes not being reflected, try adding this method to your script. Please note that this method does not remove the mappings from symbolic template names to filenames; use clearTemplate() for that.

This replaces the clear_tpl() method of the old class.
Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
See also:
setTemplate($aList)

clearTemplate($aToken)

Definition at line 1678 of file FastTemplate.php.

Referenced by clear().

FastTemplate::clearTemplate ( $ aToken = '' )

Clear the internal mapping-list of symbolic template names to file names as defined with setTemplate().

There are three ways to call this method:

$tpl->clearTemplate();
If the $aToken argument is unset or empty then all mappings of symbolic template names (both dynamic and static ones) to filenames are removed from memory.
$tpl->clearTemplate('name');
If the specified $aToken is a symbolic template name (i.e. a string) the named template mapping is removed.
$tpl->clearTemplate(array('foo', 'bar'));
Passing an array of symbolic template names will remove all template mappings named by that array.

Note: The internal list holding the loaded (i.e. parsed) templates is not touched by this method; use clearLoaded($aToken) for that. - Example:

    $templates = array(
        'MAIN' => 'main.tpl',
        'BODY' => 'body.tpl',
        'FOOT' => 'foot.tpl');
    $tpl->setTemplate($templates);
    // some code here
     
    // remove a single symbolic template name:
    $tpl->clearTemplate('MAIN');
     
    // this would remove the templates defined before:
    $tpl->clearTemplate(array_flip($templates));
    // or (even shorter/faster) to remove all mappings:
    $tpl->clearTemplate();
 
This replaces the clear_define() method of the old class.
Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
See also:
setTemplate($aList)

getTemplate($aToken)

clearLoaded($aToken)

Definition at line 1763 of file FastTemplate.php.

Referenced by clear().

FastTemplate::clearVariable ( $ aToken = '' )

Clear variable tokens set by setVariable().

There are three ways to call this method:

$tpl->clearVariable();
If the $aToken argument is unset or empty then all values are removed. This includes variable tokens defined with setVariable(), dynamic blocks defined with setDynamic() and templates (both dynamic and static ones) loaded with parse(). Since this variant does, in fact, remove all known values from memory, you should be very carefull!
$tpl->clearVariable('NAME');
If the specified $aToken is a string the named token is removed. This may be either a variable token defined with setVariable() or parse() respectively or a dynamic block defined with setDynamic().
$tpl->clearVariable(array('FOO', 'BAR'));
Passing an array of strings will remove all variable definitions named by that array. Again, this may be either variable tokens defined with setVariable() or parse() respectively or dynamic blocks defined with setDynamic().
This replaces the clear()/clear_assign()/clear_href() methods of the old class.
Parameters:
$aToken Mixed Either empty/unset, a string or an array of strings (see explaination above).
See also:
setVariable($aToken, $aValue)

getVariable($aToken)

Definition at line 1828 of file FastTemplate.php.

Referenced by clear().

FastTemplate::fetch ( $ aToken = '',
$ stripComments = TRUE
)

Get the raw data from a parsed template.

This method returns the parsed contents of the specified $aToken which must have been passed to parse() before. Calling this method directly (or indirectly via write()) is usually the last step when using a FastTemplate instance (see the example above).

The optional $stripComments argument is a real time and money saver. It removes all valid X/HTML comments ('<!-- ... -->') from the output thus saving both transfer time and bandwidth (volume).

Parameters:
$aToken String The symbolic variable name to lookup; if unset or empty it defaults to the last target variable that was used in a call to parse().
$stripComments Boolean If TRUE (the default) all X/HTML comments are stripped from the returned data, otherwise (i.e. FALSE) the parsed data is returned as is.
Returns:
String The contents of the parsed $aToken.
See also:
parse($aTargetToken, $aSourceTemplate)

write($aToken, $stripComments)

Definition at line 1873 of file FastTemplate.php.

Referenced by write().

FastTemplate::parse ( $ aTargetToken,
$ aSourceTemplate
)

Perform the {TOKEN} to 'value' conversion within a template.

The parse() method is kind of 'main function' of this class. You won't ever use FastTemplate without calling this method at least once (and most likely more than once). It accepts two arguments where the first one defines the target token of the parsed data and the second one the source template.
There are three ways to call it:

$tpl->parse('BODY', 'main'); // regular
In the regular version, the template named 'main' is loaded (if it hasn't been already), all the variable tokens are interpolated, and the result is then stored as the value of the 'BODY' variable token. If {BODY} 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.
$tpl->parse('BODY', array('table', 'main')); // compound

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

 $tpl->parse('BODY', 'table');
 $tpl->parse('BODY', 'main');
 

is the same as:

 $tpl->parse('BODY', array('table', 'main'));
 // this form saves method calls and makes your code cleaner
 

It is important to note that when you are using the compound variant, each template after the first, must contain the variable token that you are parsing the results into; hence the order of the passed array's members is significant. In the above example, the template 'main' must contain the variable token {BODY}, as that is where the parsed results of 'table' is stored. If 'main' does not contain the variable token {BODY}, then the parsed results of 'table' will be lost.

$tpl->parse('BODY', '.row'); // append
The append style allows you to append the parsed results to the target variable token. Placing a leading dot (.) before a symbolic template name causes the method to append the parsed results of that template to the returned results. This is most useful when building tables that have a dynamic number of rows (see setDynamic() and the example above) - such as data from a database query.
Parameters:
$aTargetToken String The target variable token to be used for storing the parse result.
$aSourceTemplate Mixed Either a string holding a symbolic template name or an array of template names (see above).
See also:
setDynamic($aToken, $aTemplate)

setTemplate($aToken, $aValue)

setStrict($beStrict)

setVerbose($doPrint)

Definition at line 1970 of file FastTemplate.php.

FastTemplate::write ( $ aToken = '',
$ stripComments = TRUE
)

Print the contents of the specified $aToken.

This method is provided for convenience; it writes the parsed contents of the given variable token to STDOUT. If you need to print somewhere else (e.g. a socket or file handle) you would want to call the fetch() method to get a reference to the data first:

    $data = $tpl->fetch('BODY');
    fwrite($fd, $data); // save to a file
 
This replaces the FastPrint() method of the old class.
Parameters:
$aToken String The variable to print; if unset or empty defaults to the last variable that was used in a call to parse().
$stripComments Boolean If TRUE (the default) all valid X/HTML comments ('<!-- ... -->') are stripped from the printed data, otherwise (i.e. FALSE) the data is printed out as is.
See also:
setVariable($aToken, $aValue)

parse($aTargetToken, $aSourceTemplate)

fetch($aToken, $stripComments)

Definition at line 2049 of file FastTemplate.php.

References fetch().


The documentation for this class was generated from the following file:

Generated on 13 Dec 2006 for project  FastTemplate  with
Doxygen 1.5.1-1  corrected  by sed  and HTMLtidy   -x-