PEAR is archived and read-only

This mirror preserves historical PEAR package releases and metadata so existing references remain available.

Home » HTML » HTML_Template_IT » Manual

Introduction

Introduction – Creating and Parsing templates

Templates

A template consists of text and special labeled blocks and placeholders. The content of blocks can be re-used and parsed multiple times with different placeholder values.

A typical template

<html>
 <body>
  Userlist
  <table>
<!-- BEGIN row -->
   <tr>
    <td>{USERNAME}</td>
    <td>{EMAIL}</td>
   </tr>
<!-- END row -->
  </table>
 </body>
</html>

Placeholder

Placeholders can be defined in templates and are filled from PHP code with content. The format of placeholder up to version (1.1.x) is

{[0-9A-Za-z_-]+}

Since version 1.2.x dots are allowed, too.

{[\.0-9A-Za-z_-]+}

This means, the name of the placeholder can consist of upper- and lowercase letters, underscores and hypens. The name must be placed between curly brackets without any spaces. Valid names are i.e.:

Valid names since version 1.2.x

Non-valid names are i.e.

Blocks

The format of a block is


<!-- BEGIN [0-9A-Za-z_-]+ -->
... block content ...
<!-- END [0-9A-Za-z_-]+ -->

Since version 1.2.x dots are allowed in block definitions


<!-- BEGIN [\.0-9A-Za-z_-]+ -->
... block content ...
<!-- END [\.0-9A-Za-z_-]+ -->

The rules for the block name are the same like for placeholders. In contrast to placeholders the spaces in the block markup are required.

The nesting of blocks is permitted, but be careful while parsing. You have to set and parse the deepest inner block first and then set and parse from inner to outer.

In IT the whole template file itself is nested in a meta block called "__global__". Most block-related functions use this block name as default.

Usage Example

The template


<html> 
 <table border> 
<!-- BEGIN row --> 
  <tr>
<!-- BEGIN cell -->  
   <td>
    {DATA}
   </td>
<!-- END cell -->  
  </tr>
<!-- END row --> 
 </table> 
</html>

The script

<?php
  require_once "HTML/Template/IT.php";

  $data = array
  (
    "0" => array("Stig", "Bakken"),
    "1" => array("Martin", "Jansen"),
    "2" => array("Alexander", "Merz")
  );

  $tpl = new HTML_Template_IT("./templates");

  $tpl->loadTemplatefile("main.tpl.htm", true, true);

  foreach($data as $name) {
    foreach($name as $cell) {
        // Assign data to the inner block
        $tpl->setCurrentBlock("cell") ;
        $tpl->setVariable("DATA", $cell) ;
        $tpl->parseCurrentBlock("cell") ;
    }

     // parse outter block
     $tpl->parse("row");
  }
  // print the output
  $tpl->show();

?>

The output

   
<html>
 <table border>
  <tr>
   <td>
    Stig
   </td>
   <td>
    Bakken
   </td>
  </tr>
  <tr>
   <td>
    Martin
   </td>
   <td>
    Jansen
   </td>
  </tr>
  <tr>
   <td>
    Alexander
   </td>
   <td>
    Merz
   </td>
  </tr>
 </table>
</html>

HTML_Template_IT::HTML_Template_IT()

HTML_Template_IT::HTML_Template_IT() – constructor

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::HTML_Template_IT ( string $root = '.' )

Description

Constructor. Create a new instance of HTML_Template_IT and sets the search path for templates.

Parameter

Return value

object - a new HTML_Template_IT object

Note

This function can be called statically.

See

HTML_Template_IT::setRoot()

HTML_Template_IT::get()

HTML_Template_IT::get() – get a block including replacments

Synopsis

require_once 'HTML/Template/IT.php';

string HTML_Template_IT::get ( string $block = "__global__" )

Description

This functions return a block with all replacements done.

Parameter

Return value

string - the template with all replacements done.

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.

See

HTML_Template_IT::parse()

HTML_Template_IT::getGlobalvariables()

HTML_Template_IT::getGlobalvariables() – returns an array of all global variables from the variable cache

Synopsis

require_once 'HTML/Template/IT.php';

array HTML_Template_IT::getGlobalvariables ( )

Description

Gets an array of all global variables in the variable cache. Only variables that are filled using HTML_Template_IT::setVariable() are returned. The returned has two values. The first values holds an array with the names of the global variables, the second value holds an array with all the values.

Return value

array - An array. The key 0 holds an array with the names of all filled variables, the key 1 holds an array with names of the according values.

Example

Script

<?php

require_once("HTML/Template/IT.php");

$template = <<<EOF
<!-- BEGIN a -->
    Hello {username}
<!-- END a -->
Welcome to {page},
You are visitor number {visitorcount}.
EOF;

$tpl = new HTML_Template_IT('.');
$tpl->setTemplate($template);

// set the {page} variable. It will be returned by getGlobalvariables then.
$tpl->setVariable("page", "http://example.com");
$tpl->setVariable("username", "foo");

// getGlobalvariables won't return {username} as it is not a global variable
// It won't return {visitorcount} as it is not set
print_r($tpl->getGlobalvariables());

?>

The output

   
Array
(
    [0] => Array
        (
            [0] => @{page}@
        )

    [1] => Array
        (
            [0] => http://example.com
        )

)

Note

This function can not be called statically.

See

HTML_Template_IT::setVariable(),

HTML_Template_IT::loadTemplatefile()

HTML_Template_IT::loadTemplatefile() – load a template file

Synopsis

require_once 'HTML/Template/IT.php';

boolean HTML_Template_IT::loadTemplatefile ( string $filename , boolean $removeUnknownVariables = true , boolean $removeEmptyBlocks = true )

Description

Loads a template from a file and generates internal lists for blocks and variables.

Parameter

Return value

boolean - Returns TRUE on success, FALSE on failure.

Example

Templatefile main.tpl.htm

<html>
 <body>
User {USERNAME} logged in successfull as {ROLE}.
 </body>
</html>

Script with $removeUnknownVariables = FALSE

<?php
require_once 'HTML/Template/IT.php';

$tpl = new HTML_Template_IT('.');
$tpl->loadTemplatefile ('main.tpl.htm', false, false);

$tpl->setVariable ('USERNAME', 'foo');
// Placeholder ROLE is not set
$tpl->show();
?>

Output


User foo logged in successfull as {ROLE}.

Script with $removeUnknownVariables = TRUE

<?php
require_once 'HTML/Template/IT.php';

$tpl = new HTML_Template_IT('.');
$tpl->loadTemplatefile ('main.tpl.htm', true, true);

$tpl->setVariable ('USERNAME', 'foo');
// Placeholder ROLE is not set, but $removeUnknownVariables is set to true.
$tpl->show();
?>

Output


User foo logged in successfull as .

Note

This function can not be called statically.

See

HTML_Template_IT::setTemplate()

HTML_Template_IT::parse()

HTML_Template_IT::parse() – parse a block

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::parse ( string $block = "__global__" , boolean $flag_recursion = false )

Description

Parses the defined block, performs all substitutions and appends the result to already parsed blocks.

Parameter

Return value

boolean - Returns TRUE if there was no placeholder to substitute, otherwise FALSE or IT_Error.

Example

The template cvsnames.tpl.htm

<html>
 <table>
<!-- BEGIN row -->
  <tr>
   <td>
    {CVS_USERNAME}
   </td>
   <td>
    {REALNAME}
   </td>
  </tr>
<!-- END row -->
 </table>
</html>

The script

<?php
  require_once "HTML/Template/IT.php";

  $data = array
  (
    "0" => array("cvs_username" => "pajoye",
                 "realname" => "Pierre-Alain Joye"),
    "1" => array("cvs_username" => "dsp",
                 "realname" => "David Soria Parra")
  );

  $tpl = new HTML_Template_IT("./templates");

  $tpl->loadTemplatefile("cvsnames.tpl.htm", true, true);

  foreach($data as $name) {

     $tpl->setVariable("CVS_USERNAME", $name["cvs_username"]);
     $tpl->setVariable("REALNAME", $name["realname"]);

     $tpl->parse("row");
  }

  // show() parses the __global__ block and
  // print the output
  $tpl->show();

?>

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.

See

HTML_Template_it::parseCurrentBlock()

HTML_Template_IT::parseCurrentBlock()

HTML_Template_IT::parseCurrentBlock() – parse the current block

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::parseCurrentBlock ( )

Description

Parses the current block. The current block can be set with HTML_Template_IT::setCurrentBlock().

Return value

boolean - Returns TRUE if there was no placeholder to substitute, otherwise FALSE or IT_Error.

Example

The template cvsnames.tpl.htm

<html>
 <table>
<!-- BEGIN row -->
  <tr>
   <td>
    {CVS_USERNAME}
   </td>
   <td> 
    {REALNAME}
   </td>
  </tr>
<!-- END row -->
 </table>
</html>

Script

<?php
  require_once "HTML/Template/IT.php";

  $data = array
  (
    "0" => array("cvs_username" => "pajoye", 
                 "realname" => "Pierre-Alain Joye"),
    "1" => array("cvs_username" => "dsp",
                 "realname" => "David Soria Parra")
  );

  $tpl = new HTML_Template_IT("./templates");

  $tpl->loadTemplatefile("cvsnames.tpl.htm", true, true);

  // set the current block, which can now be used with parseCurrentBlock()
  $tpl->setCurrentBlock("row"); 
  foreach($data as $name) {
     // Assign data to the inner block

     $tpl->setVariable("CVS_USERNAME", $name["cvs_username"]);
     $tpl->setVariable("REALNAME", $name["realname"]);

     // parse the current set block
     $tpl->parseCurrentBlock();
  }

  // show() parses the __global__ block and
  // print the output
  $tpl->show();

?>

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.

See

HTML_Template_it::parse(), HTML_Template_it::setCurrentBlock()

HTML_Template_IT::setCurrentBlock()

HTML_Template_IT::setCurrentBlock() – set the current block

Synopsis

require_once 'HTML/Template/IT.php';

boolean HTML_Template_IT::setCurrentBlock ( string $block = "__global__" )

Description

Sets the name of the current block, where placeholder should be substituted. The current block can be parsed with HTML_Template_IT::parseCurrentTemplate().

Parameter

Return value

boolean - TRUE, if found and succcessful set, otherwise IT_Error will be returned.

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.

See

HTML_Template_it::parseCurrentBlock(),

HTML_Template_IT::setRoot()

HTML_Template_IT::setRoot() – set the template root directory

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::setRoot ( string $root )

Description

Sets the path to the template directory where HTML_Template_IT::loadTemplatefile() searches for templates. Every filename is prefixed with the given string.

Parameter

Example

Directorytree.


./
./testscript.php
./templates/design01/main.tpl.htm
./templates/design01/table.tpl.htm
./templates/design02/main.tpl.htm
./templates/design02/table.tpl.htm

script - testscript.php

<?php 
  /* 
   * testscipt.php - sets a random design
   */

  require_once "HTML/Template/IT.php";

  $tpl = new HTML_Template_IT();
 
  $randomNumber = (int) round(rand(0,1));
  switch ($randomNumber) 
  {
     case 0:
         // Set root to design01 so the called main.tpl.htm is searched there
         $tpl->setRoot("./templates/design01");
         break;
     case 1:
     default:
         // Set root to design02 so the called main.tpl.htm is searched there
         $tpl->setRoot("./templates/design02");
         break;
  }

  /* Loads either ./templates/design01/main.tpl.htm
   * or ./templates/design02/main.tpl.htm depending on the root directory set
   * with setRoot in the switch */
  $tpl->loadTemplatefile("main.tpl.htm", true, true);

  /* ... assign variables .. */

  // show
  $tpl->show();

?>

Note

This function can not be called statically.

See

HTML_Template_IT::HTML_Template_IT(), HTML_Template_IT::loadTemplatefile()

HTML_Template_IT::setOption()

HTML_Template_IT::setOption() – sets an option

Synopsis

require_once 'HTML/Template/IT.php';

int HTML_Template_IT::setOption ( string $option , mixed $value )

Description

Sets an option. Please notice that changing some option might result in an unexpected behaviour of HTML_Template_IT.

Return value

int - Returns 1 on success, otherwise an IT_Error object.

Parameter

Options

Currently setOption allows to set only two options. Instead of using this method, access the properties directly on the template object.

Possible options:
Option Default value Description
removeUnknownVariables TRUE If TRUE all template variables, which are not filled, are removed while parsing. This option is usually set by calling HTML_Template_IT::loadTemplatefile() or HTML_Template_IT::setTemplate().
removeEmptyBlocks TRUE If TRUE all blocks not containing any filled template variables are removed. This option is usually set by calling HTML_Template_IT::loadTemplatefile() or HTML_Template_IT::setTemplate().
clearCache FALSE If TRUE parsed blocks are not cached. If you don't know exactly what you do, just leave the default value.
clearCacheOnParse FALSE If TRUE the variable cache will be cleaned after parsing. If you don't know exactly what you do, just leave the default value.
openingDelimiter '{' Defines the character, every template variable has to start with. If you change this value, you have to call init() to reinitialise the template. If you don't know exactly what you do, just leave the default value.
closingDelimiter '}' Defines the character, every template variable has to end with. If you change this value, you have to call init() to reinitialise the template. If you don't know exactly what you do, just leave the default value.
blocknameRegExp '[\.0-9A-Za-z_-]+' The regular expression, thats used to parse block names. If you change this value, you have to call init() to reinitialise the template. If you don't know exactly what you do, just leave the default value.
variablenameRegExp '[\.0-9A-Za-z_-]+' The regular expression, thats used to parse template variable names. If you change this value, you have to call init() to reinitialise the template. If you don't know exactly what you do, just leave the default value.

Note

This function can not be called statically.

See

HTML_Template_IT::loadTemplatefile()

HTML_Template_IT::setTemplate()

HTML_Template_IT::setTemplate()

HTML_Template_IT::setTemplate() – set a template

Synopsis

require_once 'HTML/Template/IT.php';

boolean HTML_Template_IT::setTemplate ( string $template , boolean $removeUnkownVariables = true , boolean $removeEmptyBlocks = true )

Description

Loads template from a string and controls the behavior in case of unused variables and blocks

Parameter

Return value

boolean - Returns TRUE on success, FALSE on failure.

Example

Script

<?php
  require_once "HTML/Template/IT.php";

  $data = array
  (
    "0" => array("Stig", "Bakken"),
    "1" => array("Martin", "Jansen"),
    "2" => array("Alexander", "Merz")
  );

  $templateString = <<<EOD
<html>
 <table>
<!-- BEGIN row -->
  <tr>
<!-- BEGIN cell -->
   <td>
    {DATA}
   </td>
<!-- END cell -->
  </tr>
<!-- END row -->
 </table>
</html>
EOD;


  $tpl = new HTML_Template_IT();
  $tpl->setTemplate($templateString, true, true);

  foreach($data as $name) {
    foreach($name as $cell) {
        // Assign data to the inner block
        $tpl->setCurrentBlock("cell") ;
        $tpl->setVariable("DATA", $cell) ;
        $tpl->parseCurrentBlock("cell") ;
    }

     // parse outter block
     $tpl->parse("row");
  }
  // show
  $tpl->show();

?>

Note

This function can not be called statically.

See

HTML_Template_IT::loadTemplatefile()

HTML_Template_IT::setVariable()

HTML_Template_IT::setVariable() – set a variable

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::setVariable ( mixed $placeholder , mixed $variable = "" )

Description

Set the value of a variable in the current template block. If $placeholder is an array, the key of an element is treated as a placeholder name while the value is treated as its substitution.

Parameter

Example

Template - cvsnames.tpl.htm

<html>
 <table>
<!-- BEGIN row -->
  <tr>
   <td>
    {CVS_USERNAME}
   </td>
   <td>
    {REALNAME}
   </td>
   <td>
    <ul>
    <!-- BEGIN project_row -->
     <li>{PROJECT}</li>
    <!-- END project_row -->
    </ul>
   </td>
  </tr>
<!-- END row -->
 </table>
</html>

Script

<?php
  require_once "HTML/Template/IT.php";

  $data = array
  (
    "0" => array("cvs_username" => "pajoye", 
                 "realname" => "Pierre-Alain Joye",
                 "projects" => array("PEAR", 
                                     "PEAR_Frontend_Web", 
                                     "PEAR_RemoteInstaller", 
                                      "HTML_Template_IT")),
    "1" => array("cvs_username" => "dsp",
                 "realname" => "David Soria Parra",
                 "projects" => array("HTML_Template_IT"))
  );

  $tpl = new HTML_Template_IT("./templates");

  $tpl->loadTemplatefile("cvsnames.tpl.htm", true, true);

  foreach($data as $name) {
     // Assign data to the inner block
     
     $tpl->setCurrentBlock("project_row");
     foreach ($name['projects'] as $projectname) {
         $tpl->setVariable("PROJECT", $projectname);
         $tpl->parseCurrentBlock();
     }
     
     // use the possbility to set the placeholders using an assoc array
     $tpl->setVariable(
                      array("CVS_USERNAME" => $name["cvs_username"],
                            "REALNAME" => $name["realname"])
                      );

     $tpl->parse("row");
  }

  // show() parses the __global__ block and
  // print the output
  $tpl->show();

?>

Note

This function can not be called statically.

See

HTML_Template_IT::parse()

HTML_Template_IT::show()

HTML_Template_IT::show() – print a block including replacments

Synopsis

require_once 'HTML/Template/IT.php';

void HTML_Template_IT::show ( string $block )

Description

This functions prints a block with all replacements done.

Parameter

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.

See

HTML_Template_IT::get()

HTML_Template_IT::touchBlock()

HTML_Template_IT::touchBlock() – preserve empty block

Synopsis

require_once 'HTML/Template/IT.php';

boolean HTML_Template_IT::touchBlock ( string $block )

Description

Preserves an empty template block, even if $removeEmptyBlocks is TRUE and no substition of placeholders took place.

Parameter

Return value

boolean - TRUE, if block was found, otherwise IT_Error.

Example

Template - login.tpl.htm

<html>
<body>
<!-- BEGIN login_successfull -->
You have logged in successfully!
<!-- END login_successfull -->
<!-- BEGIN login_failed -->
Login failed
<!-- END login_failed -->
</body>
</html>

Script

<?php
  require_once "HTML/Template/IT.php";

  // Remove blocks with no placeholders, or no placeholders set ($removeEmptyBlocks=true)
  $tpl->loadTemplatefile("login.tpl.htm", true, true);

  // hypothetical
  if (login_successfull($username, $password)) {
    // print login_successfull block. 
    // login_failed is removed, due to $removeEmptyBlocks = true
    $tpl->touchBlock("login_successfull");
  } else {
    $tpl->touchBlock("login_failed");
  }

  $tpl->show();

?>

Throws

Possible PEAR_Error values
Error code Error message Reason Solution
IT_BLOCK_NOT_FOUND " Cannot find this block block " The given block does not exists. Check for typing mistakes in the argument.

Note

This function can not be called statically.