PhpTempt Tutorial

Version 30

Hans Körber

Disclaimer

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.

First issued on Wednesday, 4. April 2001

Last updated on Monday, 6. January 2003

Table of contents

 

Table of contents

3

Installation

5 Prerequisites

5 Installation procedure

Introduction

8 Template file

9 Preprocessor

9 Template control script

10 The output produced by the control script

The preprocessor and the PhpTempt class

11 General Syntax

12 Usage examples

13 Including the generated PHP files

13 Including the generated Java files

Placeholders

15 Filling in values into placeholders

17 Two ways of defining placeholders in templates

Repeating blocks

19 Syntax

21 Alternative blocks

22 Nested blocks

24 The document root block

24 Comments

25 The rules for repeating blocks

Conditional blocks

27 Syntax

28 A simple example using the cond tag

29 A simple example using the check tag

References to placeholders

33 Syntax

34 Usage of fully qualified placeholders

36 References to the parent block

39 Another example for the use of the check tag

Recursion

41 Syntax

41 Depth-first traversal

44 Sorting entries example

46 Unrolling recursion

48 Restrictions on recursion

49 Relative paths in recursive templates

Known Bugs and missing Features

53 Features

54 Known Bugs

Installation

Prerequisites

In order to use PhpTempt , the following programs need to be installed on your system:

  • PHP 4.0.4pl1
  • Java 1.1

Additionally, if you configered PHP to run as a module of the Apache web server you must dispose of the following:

  • Apache 1.3.19

Installation procedure

The installation procedure is as follows:

  1. Copy the zipped tar file PhpTempt -xx.tar.gz to a directory of your choice, where xx is a synonym for the current number of PhpTempt . The directory you chose will be referred to as PhpTempt root from now on.
  2. Change to the PhpTempt root directory. Unpack the zipped tar file by entering the command

tar xzf PhpTempt -xx.tar.gz

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.

  1. Under linux create an alias tpl defined as (C-Shell)

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 .

  1. Load the configuration file php.ini into an editor and add the PhpTempt root directory to the list of directories defined by the variable include_path . Don't forget to restart the Apache Webserver if you included PHP as a module.
  2. Finally, copy the java-doc subdirectory containing the documentation of the PhpTempt Java classes into a directory that is accessible by your HTML-browser.

Introduction

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.

Template file

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 template file

<html>

<head>

<title>{WINDOWTITLE}</title>

</head>

<body>

<table width='100%' border='1'>

<!--$ begin table1 -->

<tr bgcolor='#e0e0e0'>

<td>

<!--$ var NUMBER--><b>1</b><!--$ end NUMBER-->

</td>

<td>

<!--$ var NAME--><b>a name</b><!--$ end NAME-->

</td>

</tr>

<!--$ alt table2 -->

<tr bgcolor='#909090'>

<td>

<!--$ var NUMBER--><b>1<!--$ end NUMBER-->

</td>

<td>

<!--$ var NAME--><b>another name<!--$ end NAME-->

</td>

</tr>

<!--$ end table1 -->

<table>

</body>

</html>

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:

  1. The template file viewed with Internet Explorer

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.

Preprocessor

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

tpl table.tpl

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.

Template control script

The PHP script that will add content to the template and will produce pure HTML output is shown below:

PHP control script

<?php

include (`phptempt.php');

$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++) {

if ($i % 2 == 0) {

$t->begin (`table1');

$t->addVal (`NUMBER', $i);

$t->addVal (`NAME', $names[$i]);

$t->end (`table1');

}

else {

$t->begin (`table2');

$t->addVal (`NUMBER', $i);

$t->addVal (`NAME', $names[$i]);

$t->end (`table2');

}

}

$t->out();

?>

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 output produced by the control script

Below you can see the resulting output with Internet explorer:

  1. Output resulting from a request of the control script

We will now discuss the capabilities of PhpTempt in more detail.

The preprocessor and the PhpTempt class

General Syntax

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

Usage information printed by the preprocessor

Usage:

java PhpTemptParser [ options ] file1 file2 ...

file1 file2 ...

One or more template files.

and options is one or more of the following:

-s<suffix>

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.

-d <targetDir>

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.

-j

Creates Java code in a file with suffix java and _<suffix>
added to the filename, where <suffix> is as specified by the
-s option.

-jp <container-package>

Specify a Java <container-package> for the generated Java
class (only valid in connection with the -j-option).

-D

Enters debug mode, where additional PHP code is included
in the generated files.

-b

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.

Usage examples

The command line

tpl table.tpl

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

tpl table.tpl -j

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.

The command

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

Finally, a call

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.

Including the generated PHP files

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:

Including a generated PHP file

<?php

include ("phptempt.php");

$t = new phptempt ("table.inc");

// more PHP code to follow

// ...

?>

Including the generated Java files

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).

Including a generated Java file

import phptempt.*;

public class table {

public static void main (String[] args) {

Phptempt t = new Phptempt ("table_inc");

// more Java code to follow

}

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

where the invocation of the constructor would be:

Phptempt t = new Phptempt ("tree.java.table_inc");

Placeholders

Filling in values into placeholders

The following simple example of a PHP template, simple.tpl , shall be used in an address book:


Placeholders in a template file

<html>

<head>

<title>Placeholder example</title>

</head>

<body>

Your name is {NAME}. You live at {STREET} in {TOWN}. <br>

Your job: {DESCRIPT}

</body>

</html>

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:

tpl simple.tpl

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:

PHP script to fill in values into placeholders

<?php

include (`phptempt.php');

$t = new phptempt (`simple.inc');

$a = array (`name' => `hans',

`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']);

 

$t->out ();

?>

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:

$t->out();

Two ways of defining placeholders in templates

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:

Template file with dummy text

<html>

<head>

<title>Simple placeholder example (with dummy text)</title>

</head>

<body>

Your name is <!--$ var NAME-->(a name)<!--$ end-->.

You live at <!--$ var STREET-->(a street)<!--$ end-->

in <!--$ var TOWN-->(a town)<!--$ end-->.

Your job:

<!--$ var DESCRIPT-->(A short description of what You do)<!--$ end-->

</body>

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:

Tags defined in PhpTempt

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

Repeating blocks

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.

Syntax

A repeating block, or block for short, has the following general syntax (in EBNF-like notation):

General syntax of repeating blocks

block ::=

"<!--$" "begin" blockident "-->"

body

[ "<!--$" "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:

Template to produce a list of addresses

<html>

<head><title>Addresses in a block example</title></head>

<body>

<table border="1">

<tr>

<td colspan="3">

<b>Addresses</b>

</td>

</tr>

<tr>

<td><b>name</b></td>

<td><b>street</b></td>

<td><b>town</b></td>

</tr>

<!--$ begin aBlock-->

<tr>

<td><!--$ var NAME-->a name<!--$ end--></td>

<td><!--$ var STREET-->a name<!--$ end--></td>

<td><!--$ var TOWN-->a name<!--$ end--></td>

</tr>

<tr>

<td colspan="3">

<!--$ var DESCRIPT-->This describes the person that

lives under the given address<!--$ end-->

</td>

</tr>

<!--$ end aBlock-->

</table>

</body>

</html>

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.

Filling in values into placeholders in a block

<?php

$data['name'] = array ('hans', 'dennis', 'christine');

$data['street'] = array ('hechinger', 'NN', 'NN');

$data['town'] = array ('T&uuml;bingen', 'Reutlingen', 'Paris');

$data['description'] = array (

'Software Engineer, Programmer, Database Designer',

'Programmierer, real computer nerd',

'Manager des affaires culturelles'

);

include ('phptempt.php');

$t = new phptempt ('addresses.inc');

for ($i=0; $i<sizeof($data['name']); $i++) {

$t-> begin ('aBlock');

$t->addVal ('NAME', $data['name'][$i]);

$t->addVal ('STREET', $data['street'][$i]);

$t->addVal ('TOWN', $data['town'][$i]);

$t->addVal ('DESCRIPT', $data['description'][$i]);

$t-> end ('aBlock');

}

$t->out ();

?>

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,

tpl addresses.tpl

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.

Alternative blocks

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.

Nested 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:

Template example of nested blocks

<html>

<head><title>Nested blocks example</title></head>

<body>

<table>

<tr>

<td colspan="2">

<b>Addresses</b>

</td>

</tr>

<tr>

<td><b>name</b></td>

<td><b>town</b></td>

</tr>

<!--$ begin aBlock-->

<!--$ begin nested1-->

<tr bgcolor="#909090">

<td><!--$ var NAME-->a name<!--$ end--></td>

<td><!--$ var TOWN-->a name<!--$ end--></td>

</tr>

<!--$ end nested1-->

<!--$ begin nested2-->

<tr bgcolor="#c0c0c0">

<td><!--$ var NAME-->a name<!--$ end--></td>

<td><!--$ var TOWN-->a name<!--$ end--></td>

</tr>

<!--$ end nested2-->

<!--$ begin nested3-->

<tr bgcolor="#f0f0f0">

<td><!--$ var NAME-->a name<!--$ end--></td>

<td><!--$ var TOWN-->a name<!--$ end--></td>

</tr>

<!--$ end nested3-->

<!--$ end aBlock-->

</table>

</body>

</html>

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.

Here is how to add values to the template:

The PHP control script for the 3-colour address table

<?php

$data["name"] = array ("hans", "dennis", "christine", "karl", "horst");

$data["town"] = array ("T&uuml;bingen", "Reutlingen", "Paris", "Toronto", "G&ouml;hlen");

include ("phptempt.php");

$t = new phptempt ("three-color.inc");

for ($i=0; $i<sizeof($data["name"]); $i++) {

$t->begin ("aBlock");

if ($i % 3 == 0)

$t->begin ("nested1");

else if ($i % 3 == 1)

$t->begin ("nested2");

else

$t->begin ("nested3");

$t->addVal ("NAME", $data["name"][$i]);

$t->addVal ("TOWN", $data["town"][$i]);

if ($i % 3 == 0)

$t->end ("nested1");

else if ($i % 3 == 1)

$t->end ("nested2");

else

$t->end ("nested3");

$t->end ("aBlock");

}

$t->out ();

?>

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.

The document root block

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:

$t->begin ('doc');

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:

$t->end ('doc');

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.

Comments

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:

A comment block in a template file

<html>

<head>

<title>Comment example</title>

</head>

<body>

<!--$ ignore -->

<base href="http://hans.hn.org/">

<!--$ end-->

 

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">.

</body>

Compiling this file, comment.tpl , with the template parser creates an include file without the base tag.

A comment block may not contain any PhpTempt tags.

The rules for repeating blocks

The rules to determine if a block should be printed or not are as follows:

  1. A comment block is never printed.
  2. For repeating blocks determine if the given block contains placeholders or not (whether or not values are assigned to them).
  3. If no placeholders are declared within the block then determine the number of times n that the begin method has been called on this block.
  4. Print the contents of the block (HTML code and nested blocks) n times.
  5. Nested blocks will decide for themselves if they are printed or not (ie. for each nested block start recursively with step 1, then finish).
  6. Otherwise the block contains placeholders. Determine how many values have been defined for each placeholder. m is the maximum number of values that one placeholder in the block has been assigned to.
  7. If none of the placeholders has been assigned a value ( m =0) then do not print the block.
  8. Otherwise, m >0. Print the block m times. If a value is not available for a placeholder, then the framework will occasionally issue a warning, if you entered the debug mode of PhpTempt , that is likely to corrupt your HTML outputs and leave your script inoperable.
  9. Nested blocks will decide for themselves if they will be printed or not (ie. for each nested block restart at step 1).

Conditional blocks

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.

Syntax

The general syntax of conditional blocks in a template file is as follows:

General syntax of conditional blocks

conditional ::= ( conditional_ident | conditional_check );

 

conditional_ident ::=

"<!--$" "cond" [ "!" ] ident ( ident )* "-->"

body

"<!--$" "end" [ "!" ] ident ( ident )* "-->" ;

 

conditional_check ::=

"<!--$" "check" [ "!" ] placeholder ( placeholder )* "-->"

body

"<!--$" "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,

Negation of a condition

<!--$ check ! c1 c2 -->

...

<!--$ end-->

will only be printed if none of the conditions c1 and c2 have been set by the controlling PHP script.

A simple example using the cond tag

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:

Conditional block in a template file using the cond tag

<html>

<head><title>Conditional block example</title></head>

<body>

<!--$ cond admin-->

<a href="change.php">change entry</a>

<!--$ end admin-->

<!--$ cond admin user-->

<a href="view.php">view entry</a>

<!--$ end admin user-->

<!--$ cond error-->

The following error occurred: '{ERR}'.

<!--$ end error-->

</body>

</html>

The PHP script to control the template above (stored as, say, cond.tpl ) would look somewhat like:

PHP script to control conditional blocks

<?php

include ("phptempt.php");

$t = new PhpTempt ("cond.inc");

if (isset($id)) {

if ($id==1) /* admin condition? */

$t->setCond ("admin");

else if ($id==2) /* user condition? */

$t->setCond ("user");

else { /* error condition! */

$t->addVal ("ERR", "Illegal value for \$id: $id");

$t->setCond ("error");

}

}

else { /* no $id provided, error condition! */

$t->addVal ("ERR", "Please supply value for parameter \$id.");

$t->setCond ("error");

}

$t->out ();

?>

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.

A simple example using the check tag

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:

Example of using the check tag

<html>

<head><title>Check block test</title></head>

<body>

<table border="1" width="60%">

<tr>

<td width="30%"><b>Name</b></td>

<td width="70%"><b>Projects</b></td></tr>

<!--$ begin nameblock-->

<tr>

<td valign="top">

<!--$ var NAME-->Hans<!--$ end NAME-->

</td>

<td>

<!--$ begin projectblock-->

<!--$ var PROJECT-->Name of a project<!--$end-->

<!--$ check READY CANCELLED-->

(

<!--$ end READY CANCELLED-->

<!--$ check CANCELLED-->

<em>cancelled</em>

<!--$ check READY-->,<!--$ end READY-->

<!--$ end CANCELLED-->

<!--$ check READY-->

<em>finished</em>

<!--$ end READY-->

<!--$ check READY CANCELLED-->

)

<!--$ end CANCELLED READY --><br>

<!--$ end projectblock-->

</td>

</tr>

<!--$ end nameblock-->

</table>

</body>

</html>

The PHP script to control the template above is depicted below:

PHP control script for the check tag example

<?php

include ("phptempt.php");

$t = new phptempt ("check-block.inc");

// data:

$names = array ("Hans", "Dennis", "Matthias");

$projects = array (

"Hans" => array ("phptempt", "diff", "game"),

"Dennis" => array ("bookmarks"),

"Matthias" => array ("money", "dynamight")

);

$cancelled = array ("game" => true, "dynamight" => true);

$ready = array (

"bookmarks" => true, "money" => true, "phptempt" => true

);

// fill data into template:

for ($i=0; $i<sizeof($names); $i++) {

$name = $names[$i];

$t->begin ("nameblock");

$t->addVal ("NAME", $name);

 

for ($j=0; $j<sizeof($projects[$name]); $j++) {

$project = $projects[$name][$j];

$t->begin ("projectblock");

$t->addVal ("PROJECT", $project);

if (isset($cancelled[$project])) {

$t->addVal ("CANCELLED", "set");

}

if (isset($ready[$project]))

$t->addVal ("READY", "set");

 

$t->end ("projectblock");

}

$t->end ("nameblock");

}

$t->out();

?>

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.

  1. The output resulting from a request of the check tag example script

References to placeholders

Syntax

In PhpTempt , references to placeholders can take the following forms:

Syntax of placeholder references

placeholder ::=

"^" blockident ( "." blockident )* "#" ident

| "^" ( "." blockident )* "#" ident

| blockident ( "." blockident )* "#" ident

| 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:

Examples of fully qualified placeholder names

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:

Examples of placeholder names with relative path

^table1#name

^.table1#name

^table2#name

^#name

You may reference a placeholder in another repeating block in one of the following situations:

  • The placeholder is declared in the same block as the reference, or:
  • The placeholder is declared in one of the parent blocks of the block that contain the reference, or:
  • The placeholder is declared in a block with the same nesting level as the block which contains the reference. For example, the placeholders in the listing below have all the same nesting level of 2:
A list of placeholders with block nesting level of 2
  1. doc.blockA#ident
  2. ^blockA#ident
    (if it occurs, for example, in block doc.blockA.blockB)
  3. doc.blockB#ph
  4. ^.blockB#ph
    (if it occurs, for example, in block doc.blockA)

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.

Usage of fully qualified placeholders

Below is an example of the use of fully qualified placeholder names in a template file:

Using fully qualified names in a template

<tr bgcolor="#9090f0">

<td>

<!--$ begin referer-->

Called from {REF} (ID is {REFID}

<!--$ end referer-->

</td>

</tr>

<tr bgcolor="#c0c0f0">

<td>

Persons associated with '{NAME}' (ID is {ID}).

</td>

</tr>

<tr bgcolor="#e0e0f0">

<td>

<ul>

<!--$ begin entries-->

<li>

<a href="#?rid={doc#ID}&id={PERSONID}"

>{PERSON}</a>

</li>

<!--$ end entries-->

</ul>

</td>

</tr>

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:

PHP control script for the placeholder reference example

<?php

include ("phptempt.php");

$t = new phptempt ("fully-qualified.inc");

// array of names:

$names = array ("hans", "dennis", "christine", "karin", "heike");

// associations:

$assocs = array (

array (1, 3, 4),

array (2, 3, 4),

array (1),

array (3, 4),

array (1, 2, 3)

);

if (isset($rid)) { // set content of "referer" block

$t->begin ("referer");

$t->addVal ("REF", $names[$rid]);

$t->addVal ("REFID", $rid);

$t->end ("referer");

}

if (!isset($id)) // default for $id variable

$id = 0;

$t->addVal ("ID", $id);

$t->addVal ("NAME", $names[$id]);

// add names associated with the above to the template:

for ($i=0; $i<sizeof($assocs[$id]); $i++) {

$t->begin ("entries");

$t->addVal ("PERSON", $names[$assocs[$id][$i]]);

$t->addVal ("PERSONID", $assocs[$id][$i]);

$t->end ("entries");

}

$t->out();

?>

References to the parent block

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:

Template containing placeholder references with absolute paths

// Database entries

 

Key/Name <!--$ begin list1-->

{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,

tpl namelist.txt -j

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 :

Java source code to create output from the template

import phptempt.*;

public class namelist {

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.begin ("list1");

t.addVal ("KEY", Integer.toString(i));

t.addVal ("NAME", name[i]);

t.end ("list1");

t.begin ("list2");

if (email[i]==null)

t.addVal ("EMAIL", "no email");

else

t.addVal ("EMAIL", email[i]);

t.end ("list2");

}

t.write ("namelist.out");

}

}

To compile this Java program in, say, namelist.java , type

javac -classpath /usr/local/phptempt namelist.java

Here is the output of the program:

Output of the Java program of See Java source code to create output from the template

// Database entries

 

Key/Name

0 Hans

1 Peter

2 Christine

 

Key/Email

0 Hans.Koerber@web.de

1 no email

2 no email

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:

Number of calls of the begin method for each block

doc [1]

list1 [1]

0 Hans

list2 [1]

0 Hans.Koerber@web.de

list1 [2]

1 Peter

list2 [2]

0 no email

list1 [3]

1 Christine

list2 [3]

0 no email

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.

 

// Database entries

<!--$begin additional-->

Key/Name <!--$ begin list1-->

{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.

Another example for the use of the check tag

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:

How to simulate cond blocks with check blocks

<html>

<head><title>Check block replaces cond block</title></head>

<body>

<!--$ check ADMIN-->

<a href="#">[view secret]</a>

<!--$ end ADMIN-->

<table>

<tr>

<td width="100"><b>Name</b></td>

<td width="200"><b>EMail</b></td>

<!--$ check ADMIN-->

<td width="200"><b>Secret</b></td>

<!--$ end ADMIN-->

</tr>

<!--$ begin entry-->

<tr>

<td><!--$ var NAME-->a name<!--$ end NAME--></td>

<td><!--$ var EMAIL-->aname@address.net

<!--$ end EMAIL--></td>

<!--$ check doc#ADMIN--><td>

<!--$ var SECRET-->Secret<!--$ end SECRET-->

</td><!--$ end doc#ADMIN-->

</tr>

<!--$ end entry-->

</table>

</body>

</html>

The figure below shows the control script for the example above, fully-qualified-check.php .

Control script for the cond block simulator

<?php

include ("phptempt.php");

$t = new phptempt ("fully-qualified-check.inc");

if (isset($admin))

$t->addVal ("ADMIN", 1);

for ($i=0; $i<10; $i++) {

$t->begin ("entry");

$t->addVal ("NAME", "name-$i");

$t->addVal ("EMAIL", "name-$i@x.y");

if (isset($admin))

$t->addVal ("SECRET", "secret-$i");

$t->end ("entry");

}

$t->out();

?>

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".

Recursion

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.

Syntax

Recursion occurres where a container block is referenced from within itself. The syntax of such a recursive reference is as follows:

General syntax of recursive references

rec_reference ::=

"<!--$" "rec" [ qualifiedIdent ] "-->"

text (no PhpTempt tags) that will not be printed

"<!--$" "end" [ qualifiedIdent ] "-->"

For a list of restrictions refer to See Restrictions on recursion.

Depth-first traversal

The listing below shows the standard way in which recursion is employed in PhpTempt :

Using recursion in PhpTempt

<html>

<head>

<title>Files in directory {FOLDERNAME}</title>

</head>

<body>

<!--$ begin dirlist-->

<table>

<tr>

<td>

<IMG SRC="/icons/folder.gif" ALT="[DIR]">

</td>

<td>

<b><!--$ var FOLDERNAME-->

folder name<!--$ end FOLDERNAME--></b>

</td>

<td>&nbsp;</td>

</tr>

<!--$ begin entry-->

<tr>

<td>&nbsp;</td>

<td colspan="2">

<!--$ check NOACCESS-->

<em>Access denied</em>

<!--$ end NOACCESS-->

<!--$ rec doc.dirlist-->

<table bgcolor="#E0E0E0">

<tr><td>Recursive area, contains

subdirectory and file lists

</td></tr>

</table>

<!--$ end doc.dirlist-->

<!--$ begin textfile-->

<table>

<td>

<img src="/icons/text.gif" alt="[FILE]">

</td>

<td>

<!--$ var NAME-->

textfile.name<!--$ end NAME-->

</td>

</table>

<!--$ end textfile-->

</td>

</tr>

<!--$ end entry-->

</table>

<!--$ end dirlist-->

</body></html>

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:

Using recursion in a control script

<?php

include ("phptempt.php");

 

function listfolder ($dirpath)

{

global $t;

global $con;

static $count = 0; // debug

 

$t->begin ("dirlist");

$t->addVal ("FOLDERNAME", $dirpath);

 

// open folder; if an error occurres on attempt to open folder,

// then issue a message:

//

$dir = @opendir ($dirpath);

if (is_bool($dir) && !$dir) {

$t->begin ("entry");

$t->addVal ("NOACCESS", ++$count);

$t->end ("entry");

}

 

// otherwise, print contents of folder:

else {

while ($file = readdir ($dir)) {

// ignore . and .. entries:

if ($file=="." || $file=="..")

continue;

 

$filepath = "$dirpath/$file";

$t->begin ("entry");

if (is_dir($filepath)) {

// recursively list subfolder:

listfolder ($filepath);

}

else if (is_file($filepath)) {

$t->begin ("textfile");

$t->addVal ("NAME", $file);

$t->end ("textfile");

}

$t->end ("entry");

}

$dir = closedir ($dir);

}

$t->end ("dirlist");

}

 

$t = new phptempt ("list_dir.inc");

$rootfolder = "/home";

$t->addVal ("FOLDERNAME", $rootfolder);

 

// recursively add contents of project root directory, print template:

listfolder ($rootfolder);

$t->out();

?>

The example is quite complete. The figure below presents a screenshot of the output of this script on a (hypothetical) linux machine.

  1. Example output of a recursive page

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.

Sorting entries example

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:

Template for dividing into files and subdirectories

<html>

<head>

<title>Files in directory {FOLDERNAME}</title>

</head>

<body>

 

<!--$ begin dirlist-->

<table>

<tr>

<td><img src="/icons/folder.gif" alt="[DIR]"></td>

<td>

<b><!--$ var FOLDERNAME-->

folder name<!--$ end FOLDERNAME--></b>

</td>

<td>&nbsp;</td>

</tr>

<tr>

<td>&nbsp;</td>

<td colspan="2">

<!--$ check NOACCESS-->

<em>Access denied</em>

<!--$ end NOACCESS-->

<!--$ begin textfile-->

<table>

<td>

<img src="/icons/text.gif" alt="[FILE]">

</td>

<td>

<!--$ var NAME-->

textfile.name<!--$ end NAME-->

</td>

</table>

<!--$ end textfile-->

<!--$ rec-->

<table bgcolor="#E0E0E0">

<tr><td>Recursive area, contains subdirectory

and file lists</td></tr>

</table>

<!--$ end-->

</td>

</tr>

</table>

<!--$ end dirlist-->

</body></html>

The listing below shows the control script:

Control script for the divider template above

<?php

include ("phptempt.php");

 

function listfolder ($dirpath)

{

global $t;

global $con;

static $count = 0; // debug

 

$t->begin ("dirlist");

$t->addVal ("FOLDERNAME", $dirpath);

// open folder; if an error occurres on attempt to open folder,

// then issue a message:

$dir = @opendir ($dirpath);

if (is_bool($dir) && !$dir) {

$t->addVal ("NOACCESS", ++$count);

}

// otherwise, print contents of folder:

else {

while ($file = readdir ($dir)) {

// ignore . and .. entries:

if ($file=="." || $file=="..")

continue;

$filepath = "$dirpath/$file";

if (is_dir($filepath)) {

// recursively list subfolder:

listfolder ($filepath);

}

else if (is_file($filepath)) {

// print textfile:

$t->begin ("textfile");

$t->addVal ("NAME", $file);

$t->end ("textfile");

}

}

$dir = closedir ($dir);

}

$t->end ("dirlist");

}

 

$t = new phptempt ("list_dir_div.inc");

$rootfolder = "/var/projects/phptempt";

$t->addVal ("FOLDERNAME", $rootfolder);

 

// recursively add contents of project root directory, print template:

listfolder ($rootfolder);

$t->out();

 

?>

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.

Unrolling recursion

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.

Unrolling recursion
  1. <?php
  2.  
  3. include ("phptempt.php");
  4. $t = new phptempt ("list_dir_div.inc");
  5.  
  6. $t->begin (" dirlist ");
  7. $t->addVal ("FOLDERNAME", "/home");
  8. $t->begin ("textfile");
  9. $t->addVal ("NAME", "user.txt");
  10. $t->end ("textfile");
  11. $t->begin ("textfile");
  12. $t->addVal ("NAME", "readme");
  13. $t->end ("textfile");
  14. $t->begin (" dirlist ");
  15. $t->addVal ("FOLDERNAME", "/home/christine");
  16. $t->addVal ("NOACCESS", true);
  17. $t->end (" dirlist ");
  18. $t->begin (" dirlist ");
  19. $t->addVal ("FOLDERNAME", "/home/claus");
  20. $t->begin (" dirlist ");
  21. $t->addVal ("FOLDERNAME", "/home/claus/cpp");
  22. $t->begin ("textfile");
  23. $t->addVal ("NAME", "fold.cpp");
  24. $t->end ("textfile");
  25. $t->begin ("textfile");
  26. $t->addVal ("NAME", "fold.h");
  27. $t->end ("textfile");
  28. $t->end (" dirlist ");
  29. $t->begin ("textfile");
  30. $t->addVal ("NAME", ".exrc");
  31. $t->end ("textfile");
  32. $t->end (" dirlist ");
  33. $t->begin (" dirlist ");
  34. $t->addVal ("FOLDERNAME", "/home/hans");
  35. $t->begin ("textfile");
  36. $t->addVal ("NAME", ".exrc");
  37. $t->end ("textfile");
  38. $t->end (" dirlist ");
  39. $t->end (" dirlist ");
  40.  
  41. $t->out();
  42.  
  43. ?>

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.

Restrictions on recursion

There are few restrictions to recursion that concern the use of recursive references:

  • Each block may contain only one recursive reference. Otherwise, PhpTempt would not be able to determine which of the references to replace by a recursive block.
  • A rec tag cannot refer to a block other than an embedding block. If it references the direct embedding block, the block qualifier may be omitted. Otherwise, the qualified name of the block referenced in the rec tag must be a prefix of the fully qualified name of the block that contains the tag.

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.

Prefix rule

<!--$ begin header-->

Header for {LISTNAME}.

<!--$ end header-->

<!--$ begin list-->

... some HTML code

<!--$ begin entry-->

<!--$ rec doc.list-->

recursive part (this text will not be visible in the

output of the template)

<!--$ end doc.list-->

... some more HTML code

<!--$ end list-->

  • The doc block (See The document root block) can be the target of a recursive reference. Since this block usually contains the html -, head - and body -tags, referencing it is thoroughly discouraged.

Relative paths in recursive templates

Reuse of recursive templates necessitates employment of placeholders with relative paths. Consider the following template file:

Absolute paths in a recursive template

<!--$ 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<!--$

end--><!--$ end list2-->

 

<!--$ rec doc.recBlock-->recursive block

<!--$ end doc.recBlock-->

<!--$ end recBlock-->

This template contains placeholder references with absolute path embedded in a recursive block. Using the Java program below,

Java program for the template file with absolute path in the placeholder

import phptempt.*;

public class otherblock {

public static void main (String[] args)

{

Phptempt t = new Phptempt ("otherblock_inc");

t.begin ("recBlock");

for (int i=0; i<2; i++) {

t.begin ("list1");

t.addVal ("NAME", ""+(char)(i+65));

t.addVal ("NUMBER", Integer.toString(i));

t.end ("list1");

}

for (int i=0; i<3; i++) {

t.begin ("list2");

t.addVal ("ABBREV", "Ko"+i);

t.end ("list2");

}

// recursive:

t.begin ("recBlock");

for (int i=2; i<5; i++) {

t.begin ("list1");

t.addVal ("NAME", ""+(char)(i+65));

t.addVal ("NUMBER", Integer.toString(i));

t.end ("list1");

}

for (int i=2; i<5; i++) {

t.begin ("list2");

t.addVal ("ABBREV", "Ko"+i);

t.end ("list2");

}

t.end ("recBlock");

// end recursive

t.end ("recBlock");

t.write ("otherblock.out");

}

}

we obtain an output that I find very counter-intuitive:

Output of the preceding Java program

A: 0

B: 1

A has been set:

A: Ko0

B has been set:

B: Ko1

No value for doc.recBlock.list1#NAME has been set

C: 2

D: 3

E: 4

A has been set:

A: Ko2

A has been set:

A: Ko3

A has been set:

A: Ko4

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:

Number of calls to method begin for each template block

[1] recBlock

[1,1] list1

A: 0

[1,2] list1

B: 1

[1,1] list2

A has been set:

A: Ko0

[1,2] list2

B has been set:

B: Ko1

[1,3] list2

No value for doc.recBlock.list1#NAME has been set

[1,1] recBlock

[1,1,1] list1

C: 2

[1,1,2] list1

D: 3

[1,1,3] list1

E: 4

[1,1,1] list 2

A has been set:

A: Ko2

[1,1,2] list 2

A has been set:

A: Ko3

[1,1,3] list 2

A has been set:

A: Ko4

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:

Use of relative paths in placeholder references

<!--$ 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

! ^recBlock.list1#NAME-->

No value for ^recBlock.list1#NAME has been set<!--$

end--><!--$ end list2-->

 

<!--$ rec ^.recBlock-->recursive block

<!--$ end ^.recBlock-->

<!--$ end recBlock-->

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:

Output of the Java program using the new template

 

A: 0

B: 1

A has been set:

A: Ko0

B has been set:

B: Ko1

No value for ^recBlock.list1#NAME has been set

C: 2

D: 3

E: 4

C has been set:

C: Ko2

D has been set:

D: Ko3

E has been set:

E: Ko4

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).

Known Bugs and missing Features

Features

There are some features that I would like to add to PhpTempt (in the order of priority that I give to them):

  • Reimplement PhpTempt using PhpTempt . This is a precondition for the implementation of the following feature:
  • Port PhpTempt classes to C++. Add mechanism to produce C++ code from the template files. Compiled C/C++ code executes about 10 times faster than Java code.
  • Add command line options to enclose PhpTempt commands in template files using some alternatives, for example /**$ ... */ or //$ .. . The HTML-like tags used for the moment look really strange to me.
  • Implement placeholder references wth relative path in PHP. The parser will complain if you try to generate PHP code from a template that contains relative placeholder references.
  • Add new command line option that sets a random large integer as the name of each element. This is similar to the command line option that sets the name of each element to its fully qualified path. An option that merly serves debugging purposes.
  • Add compiling instructions as comments to the preprocessed Java template file. If some day you find a Java or PHP code in one of your directories, you would perhaps like to know what it once was good for and how to make it work?

Known Bugs

There are also some bugs that I have recognized but cannot put my fingers on exactly to find a solution:

  • Blocks containing conditional check blocks and placeholders are not printed if only the variable declared in the check block is set. The block should be printed in this case.
  • Nested blocks with name doc are possible, provided that they don't have the document root block as parent. A template such as the one defined below would be ineffective and useless:
Bug: Nested block with name "doc"

<html>

<body>

<!--$ begin doc -->

<!-- more HTML code -->

This is a {PLACEHOLDER}.

<!-- more HTML code -->

<!--$ end doc -->

The problem with this template is that

  1. A call to the begin method of PhpTempt on the doc block will be ignored even if the document root block has been entered explicitly with another call to begin .
  2. The fully qualified name of the placeholder is

doc.doc#PLACEHOLDER

  1. Because application of begin to the doc block will be ignored, and the nested block doc.doc can never be reached, the placeholder declared within that block will never be defined and thus the block will never actually be printed.

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.

4. This is meant to help you identify logical contradictions within the structure of a template.

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).

6. In this case, of course, both of them.

7. Another, more imperative, reason for the use of placeholders will be given in paragraph See Relative paths in recursive templates.