class.rFastTemplate.php Documentation
Synopsis
// Creating a template object.
require ('class.rFastTemplate.php');
$template = array ('.', 'template/fancy', 'template/simple');
$t = new rFastTemplate ($template);
$t->set_root ($template);
// Declaring templates.
$t->define (array ('main' => 'index.thtml',
'motd' => 'motd.thtml'));
$t->define (array ('list' => 'index.thtml'), true);
$t->define_dynamic ('table', 'main');
$t->define_nofile (array ('main' => $main_string), true);
$t->define_raw (array ('main' => $main_string), true);
// Assigning/clearing template variables.
$t->assign (TITLE, 'Hello, World!');
$t->setkey (TITLE, 'Hello, World!');
$value = $t->get_assigned (TITLE);
$value = $t->getkey (TITLE);
$t->unsetkey (TABLE);
$t->clear_href (TABLE);
// Substituting variables into a template.
$t->parse (MOTD, 'motd');
$t->subst (MOTD, 'motd');
$t->parse (array (MAIN => 'main', MOTD => 'motd'));
// Obtaining the output from completed template.
$t->xprint (MAIN);
$t->FastPrint ();
$string = $t->fetch ();
// Clearing/resetting a template.
$t->clear ('main');
$t->clear (array ('main', 'motd'));
$t->unload ('main');
$t->clear_dynamic ($template);
// Template debugging options.
$t->debug ('parse');
$t->debug ('parse', false);
$t->debugall ();
$t->debugall (false);
$t->debugfile ($path);
$t->logwrite ($message);
// Template parsing options.
$t->no_strict ()
$t->strict ();
$t->quiet ();
$t->dynamic (false);
$t->missing_dir_okay (true);
// Other internal functions.
$t->FindTemplate ($file);
$t->load ($file);
$t->parse_internal ($tag);
$t->parse_internal_1 ($tag, $rest = '');
Functions/Methods
rFastTemplate
Creates a new rFastTemplate object.
class rFastTemplate ([mixed TEMPLATE_PATH]);
If $template_path is omitted, it must be defined via set_root before calling define. If $template_path is a scalar, it is taken to be the path where the define'd templates should be found. If it an an array, it is taken as a list of directories which will be searched to located define'd templates.
set_root
Set the root directory which will be searched for any define'd templates.
void set_root (mixed TEMPLATE);
TEMPLATE may be a scalar in which case it is the name of the directory where the templates will be stored. If TEMPLATE is an array, the elements are the names of directories which will be searched in sequence to find the template files. See also missing_dir_okay.
About Multi template-roots
The most obvious use for multi template-roots are for website theming. The array of template roots are searched in order of being listed for a matching filename (that filename may also include a relative path). This leads to the advantage that entire groups of templates do not have to be duplicated, only templates that have changed. Others which would be the same will be 'fallen-back' to.
Example of multi template-roots
In the examples below, set_root is given an array argument which holds a list of directories which will be searched when trying to find the templates declared via define. In the first example, template/fancy/ need only contain a index.thtml if, say, the other templates were identical beween the two. In the second example, template/simple is assumed to contain a generic set of template while $HolidayThemeDir holds holiday specific templates.
// PHP 4; PHP 3 uses require().
require_once ('class.rFastTemplate.php');
$t = new rFastTemplate ($template);
// Example 1: look in 'template/fancy' then fall back to 'template'.
$t->set_root (array ('template/fancy/',
'template/'));
// Example 2: directory names may be passed via variables to set a
// holiday theme, e.g., 'template/Xmas/', 'template/Valentines/' etc.
// Fallback is as before. If any of the directories do not exist,
// they will be skipped.
$t->set_root (array ($HolidayThemeDir,
'template/simple/'));
// Declare some templates; paths are relative to the declared root(s).
$t->define (array ('main' => 'index.thtml',
'motd' => 'motd.thtml',
'weather' => 'weather/weatherforcast.thtml'));
// 'list' is a dynamic template contained in the file 'index.thtml'
$t->define (array ('list' => 'index.thtml'), true);
// 'table' is also a dynamic template. 'main' must be declared via
// define() because loading 'table' will check to see what
// file 'main' was declared to use.
$t->define_dynamic ('table', 'main');
define
Define an association between a template name and a template file.
void define (array TEMPLATE [, boolean DYNAMIC = false]);
$template is an array of one or more elements whose keys are the names of the templates and whose values are the associated files. $dynamic is an informational declaration that tells the class that the templates being defined are not independent but are inferior templates embedded within a parent template.
It is not necessary to declare any dynamic/inferior templates; they will be automatically found when the parent template is loaded. However, if you wish to predeclare many templates only some of which will be actually be used, declaring the dynamic templates can greatly reduce the amount of file I/O that takes place. The reason for this is simple: if you try to parse an undeclared dynamic template, class.rFastTemplate.php will have to load each of the declared templates until it finds the one being parsed. If you have tens or hundreds of predeclared templates, this can generate a lot of file I/O as well as waste CPU and memory loading files which are ultimately discarded. On the other hand, if you have only a couple of templates, all of which are actually used, there is no benefit to explicitly declaring dynamic templates. There is almost no cost to actually do so however (see code).
define_dynamic
Declare a dynamic template and its associated parent template.
void define_dynamic (mixed TEMPLATE [, string PARENT]);
This function is for compatibility with class.FastTemplate.php3 where declaring dynamic templates is required. With class.rFastTemplate.php, this declaration is not required, but can optimize the template loading process; see define for more details.
This function call can take two forms:
- declare one dynamic template and its the parent
- declare multiple dynamic templates and their parents
Here is an example of each:
// Single dynamic template and its parent.
define_dynamic ('dyn1', 'parent1');
// Multiple dynamic templates and their parents.
define_dynamic (array('dyn1' => 'parent1',
'dyn2' => 'parent2'));
define_nofile
See define_raw.
define_raw
This provides a way to define a template without having to read the template contents from a file.
$t->define_raw (array TEMPLATE [, boolean DYNAMIC]);
The first argument is an array of template definitions just like define except instead of having a template name point to a file it points to a string:
$t->define_raw (array ('main' => $main, 'trailer' => $trailer));
The dynamic flag defaults to false and the state is automatically set to 'loaded'. Use this if you store your templates elsewhere, e.g., a database. Another use is to create a template from a partially parsed template which still has template forms (bracket-enclosed variables) and then reparse using the newly created template, that is,
$t->define (array ('main' => 'main.thtml'));
// Do all your normal processing and assigning.
// ....
$t->parse ('MAIN', 'main');
$t->define_raw (array ('content' => $t->fetch ('MAIN')));
// Now process the "raw" template.
// ....
$t->parse ('CONTENT', 'content');
$t->FastPrint ();
assign
assign sets the value of a template variable for use during the parse/substitution phase. Internally, the function is setkey.
$somevariable = "some value";
$t->assign (MYVAR, "some value");
$t->setkey (MYVAR, "some value");
$t->assign (MYVAR, $somevariable);
$t->setkey (MYVAR, $somevariable);
$t->setkey (array (MYVAR => $somevariable));
$t->assign (array (MYVAR1 => "one",
MYVAR2 => "two"));
All of the calls above, except the last, are equivalent. The last call illustrates how one can assign multiple variable with a single call.
setkey
See assign. In hindsight, perhaps this should have been called setval.
get_assigned
This allows you to retrive the value of a previously assigned variable. It is completely equivalent to getkey. You should note that get_assigned will only retrive the value associated with a variable set via setkey or assign. This is the only place where the results of parse and assign are treated differently.
$somevariable = $t->get_assigned (MYVAR);
$somevariable = $t->getkey (MYVAR);
getkey
See get_assigned.
clear_href
This provides a mechanism for clearing the value of a key prior to parsing a template. The primary utility of this is in the case where a variable might be used in multiple contexts or in a dynamic template where the current iteration should be empty. If no_strict has been called, this is functionally equivalent to setting the variable to be an empty string.
$t->clear_href (MYVAR);
$t->unsetkey (MYVAR);
For the no_strict case, if the variable is not set or unset, during the substitution phase, the variable will be treated as if it were assigned to an empty string.
unsetkey
See clear_href.
parse
Not yet written, try again later.
subst
See parse.
FastPrint
See xprint.
xprint
When I first wrote rFastTemplate, I found having a member function named the same as a PHP function was not a good idea. It can be made to work, but internally you keep having to say something like $this->print instead of just print. Being confused at the time, I named the function xprint to avoid the problem.
xprint will print out the contents of the specified handle. Note that variable contents will not be printed, only handles. If no handle is specified, whatever handle was last used wil be parsed will be used.
$t->define (array ('main' => 'main.thtml'));
// ....
$t->parse ('CONTENT', 'main');
// This will print the same thing twice; both xprint statements
// are equivalent.
$t->xprint ();
$t->xprint ('ROW');
fetch
fetch provides a method to retrive the current contents of a handle without having to reach behind the class interface.
$t->fetch ([string HANDLE]);
It is equivalent to $t->HANDLE[$handle] with the exception that if no handle name is specified, the last one passed to parse will be used.
$t->define (array ('main' => 'main.thtml'));
// ....
$t->parse ('CONTENT', 'main');
// This will print the same thing twice; both xprint statements
// are equivalent.
$mystring = $t->fetch ();
// You can now manipulate the "finished" template before printing.
// ....
print $mystring;
clear
This provides a method to "null out" the results of a template. This is most useful when one sub-element of a dynamic template needs to be blank.
$t->define (array ('main' => 'main.thtml'));
$t->define_dynamic (array ('row' => 'main',
'col' => 'main'));
// ....
$row = 'row';
for ($i = 0; $i < $nrows; $i++) {
$col = 'col';
for ($j = 0; $j <= $ncols; $j++) {
<determine value of element (i,j)>
if (<element i,j should be omitted>) {
$t->clear ('col');
}
$t->parse (COL, $col);
$col = '.col';
}
$t->parse (ROW, $row);
$row = '.row';
}
What is perhaps not so obvious from the above code is why you would want to use clear instead of clear_href. The latter is designed to simply clear the setting of a key from an assign call. The former will clear out the entire block inside a dynamic block including any fixed HTML that is part of that dynamic block.
unload
Not yet written, try again later.
clear_dynamic
Clears a dynamic block from a template. The intent is to remove an inferior template from a parent as it the text were never present in the first place.
$t->clear_dynamic ([string TAG]);
If TAG is NULL, clear_dyanmic will clear all result elements.
clear_dyanmic will work even if the template has already been parsed by going straight to the internal results element of the parsed template and clearing it. It will also work on templates which have not yet been loaded by forcing a load via parse_internal.
debug
Turn on diagnostic printing for a particular function. This does not enable debugging via the PHP debugging mechanism; this is purely a "print some information" function.
$t->debug (string WHAT [, boolean ON]);
The first parameter is the name of the function for which diagnostic messages should be enabled, the second is a boolean flag to indicate whether printing is being turned on (true) or off (false). Whether or not anything happens is dependent on whether or not the function supports diagnostic printing.
debugall
Sets a global flag to turn on printing in all class function which support diagnostic messages.
$t->debug ([boolean ON]);
The default is to turn on debugging. If the ON parameter is set to false, debugging is turned off.
debugfile
Specify the name of the file to which diagnostic messages should be printed.
$t->debugfile (string DEBUGFILE);
There is no default for DEBUGFILE but it is intialized in the class to /tmp/class.rFastTemplate.php.dbg. When debugging is turned on, class members which support diagnostic printing will print to this file. But be warned: don't try this on a live site! First you will significantly slow things down. Second, the output from different hits on the same page will likely be intermixed making it impossible to decypher.
logwrite
logwrite is an internal function used for all of the diagnostic print statements in rFastTemplate member functions. It is not intended to be called directly.
$t->logwrite (string MESSAGE);
logwrite opens the diagnostic file (if not already open) and write the specified text with a time stamp prepended.
strict
Sets template parsing to "strict" mode; no template variables (matching regular expressions) may be present in the final output.
$t->strict ([boolean ON]);
This is the opposite of no_strict and is the default behavior. The following two calls are equivalent:
$t->no_strict ();
$t->strict (false);
no_strict
Set template parsing to "no strict" mode. At the end of the substitution phase, any remaining template variable (matching regular expressions) will be treated as if that template variable had been assigned a value of an empty string.
$t->no_strict ();
If no_strict is not used, class.rFastTemplate.php will both complain (display an error message on the page) and leave the template variables as-is in the output. It may be desirable to separate this behavior in the future, i.e., to make it possible to leave the variables in the template but not issue an error message. Among other things, it is difficult to write templates which contain examples of templates.
quiet
One of the problems with the strict/no_strict division is that switching modes does more than one thing. When in strict mode, the template form is left intact but an error message is produced. When in no-strict mode, the error message is suppressed and the template form is removed. But what if you have a form where you expect to have things which look like template forms and you want them to be passed through?
Quiet mode allows you to do just that. It suppresses the error messages but still allows the template forms to pass through to the final output. Before I added quiet mode, I couldn't insert an actual template form (e.g., {F_SOME_FIELD}) into the HTML text of this page!
dynamic
Turn on dynamic template parsing.
$t->dynamic ([boolean ON]);
By default, dynamic template parsing is on.
missing_dir_okay
Suppress errors if the template path array has non-existent members.
$t->missing_dir_okay ([boolean ON]);
The default value for ON is true if the function is called; the default behavior for a newly created template is equivalent to missing_dir_okay(false).
I originally wrote this function to get around the problem of some dynamically generated template paths. In particular, I had some code which would prepend a template path parallel to the HTML path for every page. This let me do things like have a generic navigation menu which could be superceded by a more specific one. If the more specific one did not exist the more general one was used. However, if the template path did not exist, PHP would throw an error that prevented me from doing any processing.
FindTemplate
Not yet written, try again later.
load
Not yet written, try again later.
parse_internal
Not yet written, try again later.
parse_internal_1
Not yet written, try again later.
Known Bugs
If missing_dir_okay has called, set_root can actually produce an empty ROOT array which means no templates will exist. This can only happen if, in fact, there are no valid template locations specified in the call to set_root. Still, an error should be produced at the time set_root is called to better localize the error.
Credits and References
Jason Moore wrote the original Perl version of FastTemplate for use with mod_perl. It was last known to be available at www.sober.com.
CDI from thewebmasters.net wrote class.FastTemplate.php as PHP "port" of the original Perl version.
Alister Bulman of www.minotaur.nu contributed some cleanups and allowed the template root to be a search list (array of paths).
- Printer-friendly version
- Login to post comments

