THE INFORMATIONS IN THIS TUTORIAL ARE SUPPLIED ON AN "AS IS" BASIS WITHOUT WARRANTY OF ANY KIND, AND OBJECTIVITY SHALL HAVE NO LIABILITY OR OBLIGATION FOR DAMAGES, INCLUDING BUT NOT LIMITED TO ACTUAL, INDIRECT CONSEQUENTIAL AND INCIDENTIAL DAMAGES OCCURING OUT OF OR IN CONNECTION WITH THE USE OF THE PROGRAM, WITHOUT REGARD TO WHETHER SUCH DAMAGES WERE FORESEEABLE.
34 Usage of fully qualified placeholders
36 References to the parent block
39 Another example for the use of the check tag
In order to use PhpTempt , the following programs need to be installed on your system:
Additionally, if you configered PHP to run as a module of the Apache web server you must dispose of the following:
The installation procedure is as follows:
This creates the PhpTempt directory that contains the runtime system (PHP programs and Java class files), and a subdirectory parser that contains the preprocessor to convert templates to includable files.
alias tpl 'java -cp < PhpTempt -root>/parser PhpTemptParser'
Under Windows you may want to copy the file tpl.bat into a directory that is listed in the PATH environment variable. Load the batch file into an editor and change the first entry of the file,
set PhpTempt ROOT=< PhpTempt -root>
to the name of the directory where you installed PhpTempt .
Originally, PhpTempt was created to separate HTML output from processing code in a PHP program.
Each page produced with PhpTempt consisted of at least two files: a precompiled template file and a PHP control script that read the template, added values to it at some places specified by the programmer and produced pure HTML output.
Since version 24 PhpTempt can also be included into Java programs in order to simplify the creation of Java servlets or code generators of any kind.
A huge portion of this tutorial has been written for the original PHP version but does equally apply to the Java version since the names and usage of the PhpTempt methods are identical for both. Where necessary, the user will be notified by any difference between the two versions.
Generally speaking, the PhpTempt tool comprises a template preprocessor and a suite of classes to control the output of the template. The programmer uses only a few methods of the main class which is called phptempt ( Phptempt in the Java version) . Most of the work will be done "behind the scenes".
It is best to introduce PhpTempt by means of a simple example.1
Note: This tutorial assumes that you are a more or less experienced PHP programmer. Some examples assume that you are also familiar with the Java programming language.
The template file is essentially an ordinary HTML (or text) file augmented with special tags to denote placeholders or repeating blocks. Consider the following template in a file named table.tpl :
<table width='100%' border='1'>
<!--$ var NUMBER--><b>1</b><!--$ end NUMBER-->
<!--$ var NAME--><b>a name</b><!--$ end NAME-->
<!--$ var NUMBER--><b>1<!--$ end NUMBER-->
<!--$ var NAME--><b>another name<!--$ end NAME-->
Since browsers like Netscape Navigator or Internet Explorer interpret as comments the tags used by PhpTempt , you can view the template files with these browsers:
This is in fact one of the major benefits of PhpTempt : with its concept of nested repeating blocks delimited by comment tags, it can be used with any HTML browser and WYSIWYG HTML editor.
A preprocessor will create PHP code which you include into the PHP control script. The preprocessor is a Java application and is executed with the following DOS or UNIX command
provided the PhpTempt package has been installed properly (See Installation procedure). You should not bother with the contents of the files that the template preprocessor generates - a sequence of definitions of hashes that reflect the structure of the template file.
The PHP script that will add content to the template and will produce pure HTML output is shown below:
$t = new phptempt (`table.inc');
// define an array of names for the sample table:
$names = array (`hans', `dennis', `matthias', `benjamin', `muriel');
$t->addVal (`WINDOWTITLE', `Table Template');
// in a loop, set the NAME and NUMBER placeholders for the
// subsequent tables; switch between table1 and table2:
for ($i=0; $i<sizeof($names); $i++) {
$t->addVal (`NAME', $names[$i]);
$t->addVal (`NAME', $names[$i]);
The PhpTempt class is included in the first line of the script. The class is instantiated in the second line. Subsequent lines fill in values for the placeholders defined in the template file. The last line of the control script completes the script and prints the pure HTML code for the requested page.
The preprocessor (otherwise called template parser ) is a command line tool written in Java that can be used on either Windows or Linux/Unix, provided that a Java Runtime Environment is installed on the system.
Executing the preprocessor without command line parameters causes it to print a list of option:2
java PhpTemptParser [ options ] file1 file2 ...
and options is one or more of the following:
Adds a <suffix> to each file (after removing the original file
suffixes).
The default suffix is "inc". Please do not specify a dot with the
suffix.
Sets the target directory where to write the generated file(s)
to <targetDir>.
The default is to put the generated files into the directories of
the template files.
Creates Java code in a file with suffix java and _<suffix>
added to the filename, where <suffix> is as specified by the
-s option.
Specify a Java <container-package> for the generated Java
class (only valid in connection with the -j-option).
Enters debug mode, where additional PHP code is included
in the generated files.
Do not URL-encode the pure block contents. Escape
sequences will be interpreted as byte values, e.g. %0D as car
return. This is useful for the creation of binary files. Please
avoid using whitespaces (car return, line feed, etc). The
parser will issue warnings if it encounters whitespaces in pure
blocks with this option.
If the -d option is supplied, target-dir specifies the directory where to save the includable files generated from the template. The default action will save the generated file to the same directory as the original template.
If the -s option is supplied then suffix specifies the suffix to be appended to the name of each generated file. The default suffix is inc .
The -D option sets the debug flag for the preprocessor. If the debug flag is set then the names of the blocks and placeholders can be queried from within the methods of the phptempt.php file. This option merly serves debugging purposes.
The -j option creates a Java source file instead of a PHP include file. This option is extremely useful for code generators written in Java or to create Java servlets. An additional argument -jp that is only valid in conjunction with the Java source creation, tells PhpTempt to add a package declaration to the generated Java source.
converts the file table.tpl in the current directory to an includable file table.inc in the current directory. The same file is converted to a Java source file table_inc.java with the command
The Java class files to import by a program using PhpTempt can be found in the java-src subdirectory of the distribution. Examples of the use of this class can be found in the java-examples subdirectory. Finally, a javadoc documentation of the classes is available in the java-doc subdirectory.
tpl e:\ PhpTempt \Templates\table.tpl
converts the file table.tpl that is located in the folder e:\ PhpTempt \Templates and writes the generated file, table.inc to that very same folder. The appropriate command on a linux system would be, for example:
tpl /usr/local/projects/ PhpTempt /Templates/table.inc
tpl -d g:\php-includes -s php table.tpl selection.tpl
would start conversion of the specified files, table.tpl and selection.tpl , in the current working directory. The resulting files would be stored in the folder g:\php-includes , the names of these files being table.php and selection.php , respectively.
To include the generated files into your PHP control scripts, simply include the PhpTempt class file and instantiate the PhpTempt class. For example, to include a generated file table.inc , add the following to your control script:
To include the generated file into your Java control program, simply import the PhpTempt class in package phptempt and instantiate the Phptempt class (note the capital letter "P" at the beginning of the class name in contrast to the class name of the PhpTempt class for PHP).
public static void main (String[] args) {
Phptempt t = new Phptempt ("table_inc");
In order to be able to compile a generated Java file, you must specify the PhpTempt path with the classpath option. For the above example this is:
javac -classpath /usr/local/phptempt/java-src table_inc.java
where in this example /usr/local/phptempt is the PhpTempt root directory.
Note that, when using the -jp option, you have to specify the fully qualified class name (ie. package and class name, separated by dots) in the constructor call to the PhpTempt class. Thus, for example, to compile a template table.tpl that belongs to package tree.java , run the following commands:
tpl -j -jp "tree.java" tree/java/table.tpl
javac -sourcepath .:/usr/local/phptempt/java-src tree/java/table.php
The following simple example of a PHP template, simple.tpl , shall be used in an address book:
<title>Placeholder example</title>
Your name is {NAME}. You live at {STREET} in {TOWN}. <br>
There are three placeholders within this template file: NAME, STREET and TOWN.When defining the HTML template, you do not know where to get concrete values for these placeholders, but you do know about their concrete semantics (as the names of the placeholders suggest) and their position within the resulting HTML file.
Change to the folder in which the template resides and create an includable, simple.inc , by typing:
at the prompt of your favorite shell (See The preprocessor and the PhpTempt class).
The following PHP control script will fill in values for the placeholders from a predefined array:
$t = new phptempt (`simple.inc');
`street' => `some place', `town' => `Germany',
`what' => `Software Engineer, Programmer, Database Desinger');
$t->addVal (`NAME', $a[`name']);
$t->addVal (`STREET', $a[`street']);
$t->addVal (`TOWN', $a[`town']);
$t->addVal (`DESCRIPT', $a[`what']);
If you request the PHP script in a browser, you will see the placeholders of the template file replaced by the concrete values that you filled in using method addVal of the PhpTempt class.
A step-by-step explanation of the example follows:
First, the PhpTempt class definitions are included to the control script and an instance of the PhpTempt class is created:
include ('
PhpTempt
.php');
$t = new
PhpTempt
('simple.inc');
Behind the scenes, a representation of the template file, created by the template parser in the first place, will be read by the instance.
The next step is to start adding values to the template. For example, you replace NAME with a concrete value, 'hans', by a call to method addValue :
$t->addVal ('NAME', $a['name']);
To actually output the document with the placeholders replaced by the concrete values, you use the method out in the manner depicted below:
If you view the template file in a browser you might find how the placeholders destroy the perfect layout of the page in a somewhat annoying manner.
Usually you want to insert a dummy text that will be replaced by the actual content of the page. Dummy text portions make it easier for the designer of the page and their users to estimate the impact of the design.
Instead of adding placeholders in curly braces, in a PhpTempt template one can add dummy text associated with a placeholder. The template file from See Placeholders in a template file with dummy text instead of placeholders in curly braces is shown below:
<title>Simple placeholder example (with dummy text)</title>
Your name is <!--$ var NAME-->(a name)<!--$ end-->.
You live at <!--$ var STREET-->(a street)<!--$ end-->
in <!--$ var TOWN-->(a town)<!--$ end-->.
<!--$ var DESCRIPT-->(A short description of what You do)<!--$ end-->
If you view the above template in a browser you will only see the following text:
"Your name is (a name). You live at (a street) in (a town). Your job: (A short description of what you do)".
In contrast the text produced by the very same control script (See PHP script to fill in values into placeholders) will look like this:
" Your name is hans. You live at some place in Germany. Your job: Software Engineer, Programmer, Database Designer".
Note the somewhat strange fashion in which a PhpTempt tag is introduced. The use of <!--$ to mark a PhpTempt tag simplifies the preprocessor a lot. At the same time, browsers interpret the <!-- suffix of the tag as the beginning of a comment. This is the reason why you cannot, in general, see the PhpTempt tags when viewing a template file in a browser.3
PhpTempt defines many different tags to control the behaviour of a template file:
alt
begin
check
cond
var
rec
ignore
end
The begin and alt tags are used to define (alternative) repeating blocks and will be explained in the suite of this chapter (See Repeating blocks). The var tag is used to introduce placeholders with dummy text. check and cond check for a specified placeholder or condition, respectively, to decide if the block must be printed or not. The rec tag is used for recursion. The ignore block will simply be skipped by the preprocessor (See Comments). Finally, the end tag is used to close a block opened by one of the other tags.
Note that the identifier of the block or placeholder in the end tag is optional and can be omitted. If you choose to specify it, though (ie. if you are a defensive programmer) the identifier in the end tag and the identifier in the corresponding begin , alt or var tag must match. Otherwise the preprocessor will issue a warning.4
A repeating block in PhpTempt is a portion of a template file enclosed in begin and end tags that contains at least one placeholder or another ( nested ) repeating block. Their purpose is to repeat the contents ( body ) of the block and to print a different placeholder value in each of the repetitions.
A repeating block, or block for short, has the following general syntax (in EBNF-like notation):
"<!--$" "begin" blockident "-->"
[ "<!--$" "alt" blockident "-->" body ]
"<!--$" "end" [ blockident ] "-->"
Quotes enclose character tokens, everything within brackets is optional. Here blockident and body are nonterminals defined in an obvious way. The alt tag signifies an alternative block and will be introduced later (See Alternative blocks).
To produce a list of addresses within a simple template that augments the address book entry template (See Placeholders in a template file), a block might be used in the manner depicted below:
<head><title>Addresses in a block example</title></head>
<td><!--$ var NAME-->a name<!--$ end--></td>
<td><!--$ var STREET-->a name<!--$ end--></td>
<td><!--$ var TOWN-->a name<!--$ end--></td>
<!--$ var DESCRIPT-->This describes the person that
lives under the given address<!--$ end-->
The begin and end tag for the singlemost block aBlock in See Template to produce a list of addresses are in bold. 4 placeholders appear within the block. We will fill in values in a PHP control script for the placeholders several times in a stream-like manner. This time, though, we will insert a name, street, town and description of several people, as the PHP script below demonstrates.
$data['name'] = array ('hans', 'dennis', 'christine');
$data['street'] = array ('hechinger', 'NN', 'NN');
$data['town'] = array ('Tübingen', 'Reutlingen', 'Paris');
$data['description'] = array (
'Software Engineer, Programmer, Database Designer',
'Programmierer, real computer nerd',
'Manager des affaires culturelles'
$t = new phptempt ('addresses.inc');
for ($i=0; $i<sizeof($data['name']); $i++) {
$t->addVal ('NAME', $data['name'][$i]);
$t->addVal ('STREET', $data['street'][$i]);
$t->addVal ('TOWN', $data['town'][$i]);
$t->addVal ('DESCRIPT', $data['description'][$i]);
In See Filling in values into placeholders in a block, the calls to the begin and end methods of the PhpTempt class are in bold to demonstrate how the structure of the template file perfectly reflects the structure of the constrolling PHP script.
Within the for loop, the begin method will be called 3 times (for hans , dennis and christine ), indicating to the PhpTempt framework that block aBlock will be repeated three times, where in subsequent repetitions the data associated to hans , dennis and christine , respectively, will be inserted for the respective placeholders.
To convert the template file from See Template to produce a list of addresses, say addresses.tpl , use the template parser,
assuming the template resides in the current working directory. If you save the script from See Filling in values into placeholders in a block as addresses.php in the same folder all that remains to be done is requesting the script from within a browser to see the result.
My colleague Dennis actually convinced me to add alternative blocks to PhpTempt .
Again, consider the output in See Output resulting from a request of the control script of the table template and table control script (See table template file and See Filling in values into placeholders in a block, respectively). The control script outputs the placeholder values in two different blocks, one block being an alternative of the other. Thus, in the first iteration, the block named table1 will receive some placeholder values. In the second iteration the alternative block, table2 , will receive placeholder values, while table1 will remain empty, in the third iteration, table1 will again receive the placeholder values while table2 remains empty and so on.
Once the frameset produces HTML code with a call to the out method of PhpTempt , the body of the table1 block will be repeated multiple times. Whenever the out method (or more precisely, the out method of the object representing block table1 ) encounters a repetition of the table1 block for which none of the comprising placeholders has received a value, the method reverts to the alternative block table2 and prints its body.
Note however, that the alternative block is also only printed if at least one of the placeholders contained within, is assigned a value. Thus, if in an iteration neither table1 nor table2 contained at least one placeholder that has been assigned a value, none of the two blocks would be output in that iteration. For a thorough description of the decision algorithm for PhpTempt that determines if a block must be printed or not, See The rules for repeating blocks.
Alternative blocks are, in fact, only a shorthand for such situations in which two different outputs must be realized within subsequent iterations of the same repeating block. The general way to achive this would be to use nested blocks.
Imagine for example, in subsequent iterations of the address table you want to change between 3 different background colours of the table row. The syntax of repeating blocks in template files (See General syntax of repeating blocks) tells you that it is only possible to specify one alternative for a block. The answer to this problem is, as the title of this paragraph suggests, to use nested blocks.
The template file below demonstrates how to achive three different colours in subsequent iterations of the same repeating block:
<head><title>Nested blocks example</title></head>
<td><!--$ var NAME-->a name<!--$ end--></td>
<td><!--$ var TOWN-->a name<!--$ end--></td>
<td><!--$ var NAME-->a name<!--$ end--></td>
<td><!--$ var TOWN-->a name<!--$ end--></td>
<td><!--$ var NAME-->a name<!--$ end--></td>
<td><!--$ var TOWN-->a name<!--$ end--></td>
Note, that in order to keep the example small enough to fit one page, the original address book template was cropped down from See Placeholders in a template file.
$data["name"] = array ("hans", "dennis", "christine", "karl", "horst");
$data["town"] = array ("Tübingen", "Reutlingen", "Paris", "Toronto", "Göhlen");
$t = new phptempt ("three-color.inc");
for ($i=0; $i<sizeof($data["name"]); $i++) {
$t->addVal ("NAME", $data["name"][$i]);
$t->addVal ("TOWN", $data["town"][$i]);
Again, note how the structure of the template file in See Template example of nested blocks reflects the structure of the controlling PHP script in See The PHP control script for the 3-colour address table. The if ... else if construct assures that exactly one of the nested blocks embedded into aBlock at a time receives placeholder values. The placeholders of the other nested blocks will remain undefined and thus, these blocks will not be printed.
Each template implicitly contains a root block, doc , which in turn comprises all placeholders and nested blocks that appear anywhere in the template.You may call up method begin of the PhpTempt class on the doc block optionally:
PhpTempt calls this method on the doc block when it is first instantiated, and a subsequent call of the method on the doc block is simply ignored.5
A call to method end at the end of your control script closes the document root block:
Again, note that a call to end on the doc block is optional, since in a call to the out method, PhpTempt implicitly includes calls to the end method for blocks that have not yet been finished.
The text between (and including) the ignore -tag and the associated end -tag will be skipped when the parser creates the output file. This block type might be useful in cases where both template and generated file need be viewed in a browser but are located in different subdirectories. The comment block can then be used to enclose an HTML base tag, for example:
<title>Comment example</title>
<base href="http://hans.hn.org/">
The picture below can be found at "http://hans.hn.org/images/flash.gif" but probably not in the directory where you stored this sample file:<br>
<img src="/images/flash.gif" alt="flash icon">.
Compiling this file, comment.tpl , with the template parser creates an include file without the base tag.
The rules to determine if a block should be printed or not are as follows:
Conditional blocks either check for a specified condition to hold or for a specified placeholder to be set. The contents of conditional blocks are at most printed once.
The general syntax of conditional blocks in a template file is as follows:
conditional ::= ( conditional_ident | conditional_check );
"<!--$" "cond" [ "!" ] ident ( ident )* "-->"
"<!--$" "end" [ "!" ] ident ( ident )* "-->" ;
"<!--$" "check" [ "!" ] placeholder ( placeholder )* "-->"
"<!--$" "end" ["!"] placeholder ( placeholder )* "-->" ;
where placeholder is the name of a placeholder as defined in See Syntax of placeholder references.
ident specifies one or more conditions under which the body of the conditional block will be printed. A condition in PhpTempt template files is a simple identifier: The condition holds as soon as the PHP control script for the template has called up the setCond method of class phptempt on the appropriate condition identifier. If none of the conditions hold the block contents will not be printed.
The specification of condition identifiers in the end tag of a conditional block is optional. If specified, though, all identifiers listed in the begin tag of the conditional block must be repeated in the end tag. Otherwise, the preprocessor will issue a warning.
In contrast, placeholder (See General syntax of conditional blocks) denotes the name of a placeholder declared in the current block. The block embedded by a pair of check ... end tags will only be printed if the specified placeholder has been set with a call to method addVar in the current block iteration.
Note finally, that the list of identifiers can be preceded by an exclamation mark ("!") in the sense of a negation. The contents of a conditional block like the one in the figure below,
As an example of the use of cond tags, consider the following template that offers different interfaces to the user according to the current condition:
<head><title>Conditional block example</title></head>
<a href="change.php">change entry</a>
<a href="view.php">view entry</a>
The following error occurred: '{ERR}'.
The PHP script to control the template above (stored as, say, cond.tpl ) would look somewhat like:
$t = new PhpTempt ("cond.inc");
if ($id==1) /* admin condition? */
else if ($id==2) /* user condition? */
$t->addVal ("ERR", "Illegal value for \$id: $id");
else { /* no $id provided, error condition! */
$t->addVal ("ERR", "Please supply value for parameter \$id.");
Using method setCond of class PhpTempt , one of the conditions admin or user is set. If $id equals 1 the condition admin will hold and a call to the out method will result in an HTML file with two links, "change entry" and "view entry". In contrast, if $id equals 2 only the second link, "view entry" will be printed.
Note that only one condition can hold for a template at a time. Subsequent calls will overwrite the condition set in a previous call to setCond . If $id has not been supplied or has a value different from 1 or 2 then the error condition holds for the template in See Conditional block in a template file using the cond tag and none of the links will be printed. Instead, the script will add a value for the ERR placeholder which will be printed in the out method.
In some situations where a condition changes from one iteration to another, the check tag can be used instead of the cond tag. The figure below gives you an example:
<head><title>Check block test</title></head>
<table border="1" width="60%">
<td width="30%"><b>Name</b></td>
<td width="70%"><b>Projects</b></td></tr>
<!--$ var NAME-->Hans<!--$ end NAME-->
<!--$ var PROJECT-->Name of a project<!--$end-->
<!--$ check READY CANCELLED-->
<!--$ check READY-->,<!--$ end READY-->
<!--$ check READY CANCELLED-->
<!--$ end CANCELLED READY --><br>
The PHP script to control the template above is depicted below:
$t = new phptempt ("check-block.inc");
$names = array ("Hans", "Dennis", "Matthias");
"Hans" => array ("phptempt", "diff", "game"),
"Dennis" => array ("bookmarks"),
"Matthias" => array ("money", "dynamight")
$cancelled = array ("game" => true, "dynamight" => true);
"bookmarks" => true, "money" => true, "phptempt" => true
for ($i=0; $i<sizeof($names); $i++) {
for ($j=0; $j<sizeof($projects[$name]); $j++) {
$project = $projects[$name][$j];
$t->addVal ("PROJECT", $project);
if (isset($cancelled[$project])) {
$t->addVal ("CANCELLED", "set");
For each name in the names array the script checks for the projects associated with that name in the projects array. It prints the current name in the first table column, then in the second column prints each project associated with that person and adds the marker text cancelled and/or finished for those projects that are set to true in the cancelled and ready arrays, respectively. Note that a particular project may be contained in both arrays.
For example, in the nested loop for "Hans" the script will find that project "game" is contained in both the cancelled and the ready arrays and will thus add values for the placeholders CANCELLED and READY to the iteration of the projectblock and its embedding nameblock.
Later, when printing the contents of the template by calling up the out method, PhpTempt will actually print a parenthesis "(" after the "game" project, since at least one of the CANCELLED and READY variables has been set before6, followed by the cancelled marker text, then, as the READY placeholder has also been defined for this iteration, a comma and the ready marker text and, finally, a closing parenthesis ")".
The See The output resulting from a request of the check tag example script below shows the output of the script in a browser window.
In PhpTempt , references to placeholders can take the following forms:
"^" blockident ( "." blockident )* "#" ident
| "^" ( "." blockident )* "#" ident
| blockident ( "." blockident )* "#" ident
blockident entities of the placeholder name are called block identifiers . A sequence of such block identifiers, separated by dots (.) make up a (block) path .
Internally, PhpTempt stores placeholder names in their fully qualified form. A fully qualified placeholder starts with the document root block doc (See The document root block) and has no leading ^-Symbol. The path of these fully qualified placeholders is called an absolute path. Examples for such placeholder names are:
doc#NAME
doc#TOWN
doc.table1#NAME
doc.table2#NAME
Two placeholders declared in different blocks with the same name, for example NAME in blocks table1 and table2 (See table template file), actually denote different values.
A qualified placeholder with relative path is preceded by the ^-Symbol. It denotes a placeholder in another block relative to the block in which the reference occurs. Examples for placeholder names with relative path are:
You may reference a placeholder in another repeating block in one of the following situations:
Note that in See A list of placeholders with block nesting level of 2, the first and second as well as the third and forth placeholder, respectively, denote in fact identical placeholders.
Below is an example of the use of fully qualified placeholder names in a template file:
Called from {REF} (ID is {REFID}
Persons associated with '{NAME}' (ID is {ID}).
<a href="#?rid={doc#ID}&id={PERSONID}"
In the entries block doc#ID is a reference to a placeholder. The reference will be replaced by the value of the placeholder ID declared in the doc block when the out method of class PhpTempt is called. A PHP script that controls the template might look like as follows:
$t = new phptempt ("fully-qualified.inc");
$names = array ("hans", "dennis", "christine", "karin", "heike");
if (isset($rid)) { // set content of "referer" block
$t->addVal ("REF", $names[$rid]);
if (!isset($id)) // default for $id variable
$t->addVal ("NAME", $names[$id]);
// add names associated with the above to the template:
for ($i=0; $i<sizeof($assocs[$id]); $i++) {
$t->addVal ("PERSON", $names[$assocs[$id][$i]]);
In order to be able to "copy-and-paste" portions of one template file into another, you may want to try placeholders with relative instead of absolute paths.7
Consider the following template that is designed for use in a Java program. It contains some placeholder names with absolute paths:
{KEY} {NAME} <!--$ end list1-->
Key/Email <!--$ begin list2-->
{doc.list1#KEY} {EMAIL} <!--$ end list2-->
To be able to include the above template in a Java program as, say namelist_inc.java , first store the template under namelist.txt then use the template parser,
to generate a Java include file namelist_inc.java that contains the template. Next, compile this include file,
javac -classpath .:/usr/local/phptempt/java-src \
namelist_inc.java
The following Java source code will create a file namelist.out :
static String[] name = { "Hans", "Peter", "Christine" };
static String[] email = { "Hans.Koerber@web.de", null, null };
public static void main (String[] args) {
Phptempt t = new Phptempt ("namelist_inc");
for (int i=0; i<name.length; i++) {
t.addVal ("KEY", Integer.toString(i));
t.addVal ("EMAIL", "no email");
To compile this Java program in, say, namelist.java , type
It is interesting to note how the placeholder KEY from block doc.list1 is referenced in block list2 . To understand the referencing system, we count the number of each call to the begin method of the template t in the Java program which leads us to the situation depicted in the following list:
Since the list1 block precedes list2 in the template file, PhpTempt will print the contents of the list1 block before the contents of block list2 . On doing so, the order in which the data were injected into the blocks determines the order of the data output.
A reference of a placeholder of block list2 from within repetition i of block list2 means: print the value of that placeholder in repetition i of block list1 .
So far so good. Now imagine that we want to reuse a portion of the above template in other templates. There is no way to include templates in PhpTempt , so we use "copy-and-paste" ... and realize that we have to change every occurrence of a placeholder reference in situations where the copied portion is embedded in an additional block. This is where relative references come into play.
Consider the template depicted below. It contains the template of See Template containing placeholder references with absolute paths where the placeholder reference has slightly changed. It now refers to its target relative to the block in which it is itself contained.
{KEY} {NAME} <!--$ end list1-->
Key/Email <!--$ begin list2-->
{^.list1#KEY} {EMAIL} <!--$ end list2--><!--$end additional-->
The placeholder reference ^.list1#KEY is a reference to the block list1 in the parent block of list2 , in other words (and expressed by means of an absolute path) a reference to the placeholder doc.additional.list1#KEY . Referring back to See Template containing placeholder references with absolute paths, we simply have to replace the doc block with the ^-Symbol (pronounce: "parent block") to yield the same result as before. But this time we can copy-and-paste the whole construction without the need to change each placeholder reference from doc.list1#KEY to doc.additional.list1.KEY .
Later, in See Relative paths in recursive templates, we will get to now a more general aproach to reference placeholders relative to the current block.
Since it is possible to specify a fully qualified placeholder name in a check block, you can simulate the behaviour of a cond block with a check block referencing a placeholder declared in the doc block of the template. This can be achieved as simple as shown in the following figure:
<head><title>Check block replaces cond block</title></head>
<td width="100"><b>Name</b></td>
<td width="200"><b>EMail</b></td>
<td width="200"><b>Secret</b></td>
<td><!--$ var NAME-->a name<!--$ end NAME--></td>
<td><!--$ var EMAIL-->aname@address.net
<!--$ var SECRET-->Secret<!--$ end SECRET-->
The figure below shows the control script for the example above, fully-qualified-check.php .
$t = new phptempt ("fully-qualified-check.inc");
$t->addVal ("NAME", "name-$i");
$t->addVal ("EMAIL", "name-$i@x.y");
$t->addVal ("SECRET", "secret-$i");
Only when you specify a parameter admin when requesting the script in your browser, that is, when you call the script with the URL fully-qualified-check.php?admin=set for example, it will show you the administrator "secrets".
A container block can be referred to from within any of the embedding blocks which is called (block) recursion . The purpose of recursion in a PhpTempt template is to build documents that display hierarchically nested structures like trees or others, in a convenient way.
Recursion occurres where a container block is referenced from within itself. The syntax of such a recursive reference is as follows:
"<!--$" "rec" [ qualifiedIdent ] "-->"
text (no PhpTempt tags) that will not be printed
"<!--$" "end" [ qualifiedIdent ] "-->"
For a list of restrictions refer to See Restrictions on recursion.
The listing below shows the standard way in which recursion is employed in PhpTempt :
<title>Files in directory {FOLDERNAME}</title>
<IMG SRC="/icons/folder.gif" ALT="[DIR]">
folder name<!--$ end FOLDERNAME--></b>
<tr><td>Recursive area, contains
<img src="/icons/text.gif" alt="[FILE]">
textfile.name<!--$ end NAME-->
In the listing above, the recursive reference is printed in bold letters, as well as the beginning of the block to which it refers. A recursive reference must always refer to one of its container blocks. In the example, this is the block doc.dirlist . The rec tag could also refer to doc.dirlist.entry . Because this is the direct superblock, in this case the block identifier could be omitted. You cannot, however, refer to the doc block in a recursive reference.
The control script for the template in See Using recursion in PhpTempt is shown below:
function listfolder ($dirpath)
$t->addVal ("FOLDERNAME", $dirpath);
// open folder; if an error occurres on attempt to open folder,
$t->addVal ("NOACCESS", ++$count);
// otherwise, print contents of folder:
while ($file = readdir ($dir)) {
if ($file=="." || $file=="..")
// recursively list subfolder:
else if (is_file($filepath)) {
$t = new phptempt ("list_dir.inc");
$t->addVal ("FOLDERNAME", $rootfolder);
// recursively add contents of project root directory, print template:
The example is quite complete. The figure below presents a screenshot of the output of this script on a (hypothetical) linux machine.
As you can see the script outputs the entries in the current directory in any order. As soon as it sees a directory the script descends to that directory and outputs its contents (or issues a message if the operating system refused access to it). This is called depth-first traversal of the directory tree structure.
For the sake of readability the page should first list the files of the current directory then list the subdirectories (including their contents, again beginning with the files). We will continue to traverse the directory tree in depth-first order but will exploit a property of PhpTempt that allows for dividing of the directory contents into files and subdirectories. The listing below shows the template to accomplish this:
<title>Files in directory {FOLDERNAME}</title>
<td><img src="/icons/folder.gif" alt="[DIR]"></td>
folder name<!--$ end FOLDERNAME--></b>
<img src="/icons/text.gif" alt="[FILE]">
textfile.name<!--$ end NAME-->
function listfolder ($dirpath)
$t->addVal ("FOLDERNAME", $dirpath);
// open folder; if an error occurres on attempt to open folder,
$t->addVal ("NOACCESS", ++$count);
// otherwise, print contents of folder:
while ($file = readdir ($dir)) {
if ($file=="." || $file=="..")
// recursively list subfolder:
else if (is_file($filepath)) {
$t = new phptempt ("list_dir_div.inc");
$rootfolder = "/var/projects/phptempt";
$t->addVal ("FOLDERNAME", $rootfolder);
// recursively add contents of project root directory, print template:
The script collects all files of the current directory in the textfile block of the template and all its subdirectories in the recursive block that will be created in place of the recursive reference.
To understand how recursion works in PhpTempt it might be useful to eliminate recursive calls to the listfolder function of the script depicted in See Control script for the divider template above and to replace these with a sequence of calls to the begin and end methods of the PhpTempt class such that the script prints the structure of See Example output of a recursive page. The figure below shows the resulting script that controls the template of See Template for dividing into files and subdirectories.
To reflect the recursive structure of the original script, I indented the unrolled script according to the recursion level.
The template from See Template for dividing into files and subdirectories itself defines only the blocks doc.dirlist and doc.dirlist.textfile explicitly. As for all templates, the doc block is implicitly defined. Since the template also contains a rec tag without block identifier which automatically refers to the direct container block, doc.dirlist , an infinite number of blocks doc.dirlist.dirlist , doc.dirlist.dirlist.textfile , doc.dirlist.dirlist.dirlist , doc.dirlist.dirlist.dirlist.textfile , etc. will be available to the controlling script.
The call to the begin method of the PhpTempt instance in See $t->begin ("dirlist"); replaces the recursive reference in block doc.dirlist with a copy of this block and thus defines block doc.dirlist.dirlist as well as the embedded block doc.dirlist.dirlist.textfile and placeholders doc.dirlist.dirlist#FOLDERNAME , doc.dirlist.dirlist#NOACCESS and doc.dirlist.dirlist.textfile#NAME . Note that the block doc.dirlist.dirlist now contains the recursive reference to doc.dirlist . This recursive reference will be replaced by a block copy named doc.dirlist.dirlist.dirlist in See $t->begin ("dirlist"); where the next level of recursion is started.
There are few restrictions to recursion that concern the use of recursive references:
An example for this prefix rule is given in See Prefix rule below. The recursive reference (printed in bold) refers to the block doc.list . Since this is a prefix of the name of the container block for the reference, doc.list.entry , the prefix rule holds as would a reference to doc.list.entry or even doc . By contrast, a reference to doc.header is not valid. Here, the prefix rule would be violated.
recursive part (this text will not be visible in the
Reuse of recursive templates necessitates employment of placeholders with relative paths. Consider the following template file:
<!--$ begin recBlock--><!--$ begin list1-->
{NAME}: {NUMBER}<!--$ end list1-->
<!--$ begin list2--><!--$ check doc.recBlock.list1#NAME-->
{doc.recBlock.list1#NAME} has been set:
{doc.recBlock.list1#NAME}: {ABBREV}<!--$
end--><!--$ check ! doc.recBlock.list1#NAME-->
No value for doc.recBlock.list1#NAME has been set<!--$
<!--$ rec doc.recBlock-->recursive block
This template contains placeholder references with absolute path embedded in a recursive block. Using the Java program below,
public static void main (String[] args)
Phptempt t = new Phptempt ("otherblock_inc");
t.addVal ("NAME", ""+(char)(i+65));
t.addVal ("NUMBER", Integer.toString(i));
t.addVal ("NAME", ""+(char)(i+65));
No value for doc.recBlock.list1#NAME has been set
To understand why in the recursive block PhpTempt always outputs the value "A", we proceed as in See References to the parent block and count the number of calls to the begin method for each block in the template during execution of the Java program:
No value for doc.recBlock.list1#NAME has been set
As you can see from this listing, all the references to doc.recBlock.list1#NAME go to the placeholder NAME in the first iteration of the block doc.recBlock.list1 which is not at all what we wanted.
Use of a relative path in the placeholder, that is use of ^recBlock.list1#NAME , resolves this:
<!--$ begin recBlock--><!--$ begin list1-->
{NAME}: {NUMBER}<!--$ end list1-->
<!--$ begin list2--><!--$ check doc.recBlock.list1#NAME-->
{^recBlock.list1#NAME} has been set:
{^recBlock.list1#NAME}: {ABBREV}<!--$ end--><!--$ check
No value for ^recBlock.list1#NAME has been set<!--$
<!--$ rec ^.recBlock-->recursive block
The Java program depicted in See Java program for the template file with absolute path in the placeholder when using the new template file above finally shows the expected output, that is:
No value for ^recBlock.list1#NAME has been set
Please note also the relative path of the block in the rec tag (See Use of relative paths in placeholder references). Using relative paths you may simply "copy-and-paste" portions of a template file to another template without the need to change the placeholder or block names (See References to placeholders).
There are some features that I would like to add to PhpTempt (in the order of priority that I give to them):
There are also some bugs that I have recognized but cannot put my fingers on exactly to find a solution:
The problem with this template is that
Optionally, the parser may issue a warning if no block identifier has been specified in an end tag.
1. You will find the examples of this tutorial and other sample templates and scripts in the examples and java-examples subdirectories of the PhpTempt root folder.
2. It is assumed throughout this and subsequent chapters that you followed the installation instructions (See Installation procedure for more details).
3. You should not use dummy text placeholders within HTML's input or title tags nor within HTML forms for the very same reason. If in doubt, try for yourself.
5. Note however that nested blocks with the same name, doc , are possible, provided that they do not have the document root block as parent (See Known Bugs for additional information).
7. Another, more imperative, reason for the use of placeholders will be given in paragraph See Relative paths in recursive templates.