Class Template


Substitutes special template tags with given content.

This is just another template class for HTML/XML/text templates. BUT it is the result of studying several other template engines and tries to merge all advantages. This text explains you two things:

  1. How To Use - some examples
  2. Why This Way - good reasons for the syntax and the API
You can download this class: Feedback is very welcome: contact formular

How To Use

A usage example:

  1.  // Begin to create pure HTML. It could be like this:
  2.  $theHtmlCodeAsString = <<<EOT
  3.  <h1>Hi 'user'!</h1>
  4.  <p>This is a list of names:</p>
  5.  <ul>
  6.   <!-- BEGIN item -->
  7.   <li>'name'</li>
  8.   <!-- END item -->
  9.  </ul>
  10.  EOT;
  11.  $template = new Template($theHtmlCodeAsString);
  12.  //    or
  13.  // $template = Template::fromFile($filenameOfTemplate);
  15.  // Now let's write code to fill it with data.
  17.  // replace a variable with a value
  18.  $template->assign('user', 'Joe');
  20.  // use the subtemplate to generate three list items
  21.  $sub1 = $template->addSubtemplate('item');
  22.  $sub1->assign('name', 'Andrea');
  23.  $sub2 = $template->addSubtemplate('item');
  24.  $sub2->assign('name', 'Andy');
  25.  $sub3 = $template->addSubtemplate('item');
  26.  $sub3->assign('name', 'Anna');
  28.  // ready...
  29.  echo $template->result();
  31.  // results in
  32.  /// <h1>Hi Joe!</h1>
  33.  /// <p>This is a list of names:</p>
  34.  /// <ul>
  35.  ///  <li>Andrea</li>
  36.  ///  <li>Andy</li>
  37.  ///  <li>Anna</li>
  38.  /// </ul>

Why This Way

This class was written for a simple project. It's just one class, not a whole framework with caching and so on. It supports everything, that a simple template engine should support. But not more. Keep it simple.

Why do you use single quotes for variables?

There are three reasons:

  1. It's easy to write on most keyboards.
  2. Valid HTML will stay valid, when you insert single quotes in the text. It's also no problem to insert single quotes into a double quoted parameter value.
  3. You can prevent unintended replacements by encoding the user data via htmlentities() before inserting into the template (see example below).

Besides, if you like another syntax, just change the constants in the script. It's free.

Why don't you recommend the assignArray-method?

It's no good idea to store everything in an array. The more complex your application becomes, the harder it is to remember all the array structures. Additionally some IDEs (e.g. NetBeans) support the correct renaming of variables, but not of array indices, of course.

Assigning one variable to the template is not more complicated than a new entry in an array.

And most important: Perhaps you have a full array of data from mysql_fetch_array(). But you should not insert this into a template. Normally you have more data in there than you want to present the user. And you have to encode the user data to prevent code injection. So depending on your application, perhaps you can do something like this:

  1.   mysql_connect('localhost''test');
  2.   $result mysql_query('select "Joe<script>...</script>" as user;');
  3.   $arr mysql_fetch_array($result);
  4.   foreach ($arr as $key => $value{
  5.       $encoded htmlentities($valueENT_QUOTES'UTF-8');
  6.       $template->assign($key$encoded);
  7.   }
  8.   echo $template->result();
  10.   // results in
  11.   /// <h1>Hi Joe&lt;script&gt;...&lt;/script&gt;!</h1>
  12.   /// <p>This is a list of names:</p>
  13.   /// <ul>
  14.   ///  <li>Andrea</li>
  15.   ///  <li>Andy</li>
  16.   ///  <li>Anna</li>
  17.   /// </ul>

But this depends on your application.

Wouldn't it be nice to define conditions for subtemplates or provide something like a for-loop syntax?

No. It's a good idea to seperate PHP and HTML cleanly. So you have all your application logic in your PHP code. Your template files only define, what can be displayed and how. If you really want to script within your HTML, then you can just use PHP itself:

What is the other way?

Other interesting template classes:

Located in /Template.php (line 163)

Class Constant Summary
 SUB_PATTERN = '/(\n[\t ]*)?<!--\s*BEGIN\s+([a-z0-9_\-]+)\s*-->(.*?)(\n[\t ]*)?<!--\s*END\s+\2\s*-->/ims'
 TAG_END = "'"
 TAG_START = "'"
Method Summary
static Template fromFile (string $filename)
Template __construct (string $content)
Template addSubtemplate (string $name)
void assign (string $name, [string $value = ''])
void assignArray (array $associativeArray)
string result ()
static method fromFile (line 195)

Loads the content of a template file.

  • return: instance with the content of the template file
  • throws: Exception if $filename doesn't point to a file or reading fails (plus Exception from the constructor)
  • access: public
static Template fromFile (string $filename)
  • string $filename: path to the template file
Constructor __construct (line 211)

Creates a new instance with given string as source (not filename).

  • throws: Exception if there are ambiguous subtemplates
  • access: public
Template __construct (string $content)
  • string $content: containing the code of the template
addSubtemplate (line 242)

Subtemplates are defined once and will appear in the result zero or more times. Varying content and also sub-subtemplates are possible.

  • return: a full template instance to customize this subtemplate
  • throws: Exception if their is no such subtemplate
  • access: public
Template addSubtemplate (string $name)
  • string $name: identifyer of the subtemplate
assign (line 221)

Replaces a template tag with the given value.

  • access: public
void assign (string $name, [string $value = ''])
  • string $name: tag identifier in the template
  • string $value: new value in the document
assignArray (line 231)

Assigns all values of the given array to the keys of the array.

Warning: This function is seldom useful. Don't assign arrays from your database without encoding the data. See documentation above.

  • access: public
void assignArray (array $associativeArray)
  • array $associativeArray: of the form array( 'tag_name' => 'value' )
result (line 261)

Returns the parsed result.

  • return: actual result with all given replacements
  • access: public
string result ()
Class Constants
SUB_PATTERN = '/(\n[\t ]*)?<!--\s*BEGIN\s+([a-z0-9_\-]+)\s*-->(.*?)(\n[\t ]*)?<!--\s*END\s+\2\s*-->/ims' (line 180)

Regular expression for subtemplates.

It uses the following pattern modifiers:

  • i - caseless
  • m - multiline
  • s - dotall

TAG_END = "'" (line 171)

The beginning of a tag to substitute. Tag example: 'bar'

TAG_START = "'" (line 167)

The beginning of a tag to substitute. Tag example: 'foo'

Documentation generated on Sat, 08 Oct 2011 16:48:41 +0200 by phpDocumentor 1.4.3