PHP-HTML::Template

Documentation Page

Using the template class

Basically, you have to build a template and write a PHP script, which will open the template, assign values to the template variables, and echo the output. Go to our samples page and browse the files of the first sample to grasp the basic idea.

When creating the template object, always remember to use the =& and not the = sign:

WRONG:
$template = new Template("test.tmpl"); // wrong!
CORRECT:
$template =& new Template("test.tmpl");

If only one parameter is specified, it is taken as the template file name. In this case the template object is created with the default options. To specify other options, you pass one (associative) array, containing option=>value pairs:

$template =& new Template(array("option1"=>"value", "option2"=>"value"));

Available options are described later in this document.

Template syntax

Template syntax follows the same rules of HTML::Template except for some changes that are described below in the options section.

Methods

When the template is created, it is automatically parsed. Then you have to assign values to the template variables. To do that, you call AddParam(). AddParam() can be called in a number of ways:

  1. Setting the value of one parameter:
    // For simple TMPL_VARs:
    $template->AddParam('PARAM', 'value');
    
    // For TMPL_LOOPs:
    $template->AddParam('LOOP_PARAM', array(
                        array('PARAM' => 'VALUE_FOR_FIRST_PASS', ... ), 
                        array('PARAM' => 'VALUE_FOR_SECOND_PASS', ... )
                       ));
  2. Setting the value of a number of parameters using an associative array:
    $template->AddParam(array(
                        'PARAM'  => 'value', 
                        'PARAM2' => 'value',
                        'LOOP_PARAM' =>
                        array(array('PARAM' => 'VALUE_FOR_FIRST_PASS', ...), 
                              array('PARAM' => 'VALUE_FOR_SECOND_PASS', ...),
                              ...),
                        'ANOTHER_LOOP_PARAM' =>
                        array(array('PARAM' => 'VALUE_FOR_FIRST_PASS', ...),
                              array('PARAM' => 'VALUE_FOR_SECOND_PASS', ...),
                              ...)
                        )
                        );

To obtain the template results, you can either:

In both cases the results are kept in the $output attribute. The next time you call EchoOutput() or Output(), the results will be taken from $output without processing the template again.

You can reassign and reprocess an open template by first calling the ResetParams() and ResetOutput() methods respectively. See sample 5 of our samples page for a demonstration.

Available options

Some of the options of HTML::Template, mainly those concerning the cache, are not implemented in PHP-HTML::Template, others produce slightly different results, and others are new.

Error detection options

die_on_bad_params
If set to 0 the module will let you call $template->AddParam('param_name' => 'value') even if 'param_name' doesn't exist in the template body. Defaults to 1.
strict
If set to 0 the module will allow things that look like they might be TMPL_* tags to get by without dying. Example:
<TMPL_ LOOP NAME=ZUH>
would normally cause an error, but if you call new with 'strict'=>0, PHP-HTML::Template will ignore it. Defaults to 1.
vanguard_compatibility_mode
If set to 1 the module will expect to see <TMPL_VAR>s that look like %NAME% in addition to the standard syntax. Also sets die_on_bad_params => 0. If you're not at Vanguard Media trying to use an old format template don't worry about this one. Defaults to 0.

Caching Options

Currently there are not caching options implemented.

Filesystem Options

path
You can set this variable with a list of paths to search for files specified with the 'filename' option to new() and for files included with the <TMPL_INCLUDE> tag. This list is only consulted when the filename is relative. In the case of a <TMPL_INCLUDE> file, the path to the including file is also tried before path is consulted.
Note: Unlike in HTML::Template, the HTML_TEMPLATE_ROOT environment variable is ignored in PHP-HTML::Template.
Example:
$template =& new Template(array(
    'filename' => 'file.tmpl',
    'path'     => array('/path/to/templates', '/alternate/path')
));
search_path_on_include
If set to a true value the module will search from the top of the array of paths specified by the path option on every <TMPL_INCLUDE> and use the first matching template found. The normal behavior is to look only in the current directory for a template to include. Defaults to 0.

Debugging Options

debug
If set 1, the module will output detailed debugging information. Defaults to 0.

Miscellaneous Options

case_sensitive
Setting this option to true causes PHP-HTML::Template to treat template variable names case-sensitively. The following example would only set one parameter without the 'case_sensitive' option:
  $template =& new Template('filename', 'template.tmpl', case_sensitive', 1);
  $template->Addparam(
    'FieldA', 'foo',
    'fIELDa', 'bar',
  );
This option defaults to off.
Note: if loop_context_vars and case_sensitive options are set, the context variables are only available in lowercase.
loop_context_vars
When this parameter is set to true (it is false by default) four loop context variables are made available inside a loop: __first__, __last__, __inner__, __odd__ which can be used with <TMPL_IF>, <TMPL_UNLESS> and <TMPL_ELSE> to control how a loop is output, and other three __counter__, __pass__ and __passtotal__ which can be used with <TMPL_VAR> tags. The last two are taken from htmltmpl. __counter__ and __pass__ represent the same value. Example:
   <TMPL_LOOP NAME="FOO">
      Pass <TMPL_VAR NAME="__pass__"> of <TMPL_VAR NAME="__passtotal__"><br>
      <TMPL_IF NAME="__first__">
        This only outputs on the first pass.<br>
      </TMPL_IF>

      <TMPL_IF NAME="__odd__">
        This outputs every other pass, on the odd passes.<br>
      </TMPL_IF>

      <TMPL_UNLESS NAME="__odd__">
        This outputs every other pass, on the even passes.<br>
      </TMPL_IF>

      <TMPL_IF NAME="__inner__">
        This outputs on passes that are neither first nor last.<br>
      </TMPL_IF>

      <TMPL_IF NAME="__last__">
        This only outputs on the last pass.<br>
      <TMPL_IF>
   </TMPL_LOOP>
One use of this feature is to provide a "separator" similar in effect to the PHP function join(). Example:
   <TMPL_LOOP FRUIT>
      <TMPL_IF __last__> and </TMPL_IF>
      <TMPL_VAR KIND><TMPL_UNLESS __last__>, <TMPL_ELSE>.</TMPL_UNLESS>
   </TMPL_LOOP>
would output (in a browser) something like:
  Apples, Oranges, Brains, Toes, and Kiwi.
given an appropriate AddParam() call, of course. NOTE: A loop with only a single pass will get both __first__ and __last__ set to true, but not __inner__.
no_includes
Set this option to 1 to disallow the <TMPL_INCLUDE> tag in the template file. This can be used to make opening untrusted templates slightly less dangerous. Defaults to 0.
max_includes
Set this variable to determine the maximum depth that includes can reach. Set to 10 by default. Including files to a depth greater than this value causes an error message to be displayed.
global_vars
Normally variables declared outside a loop are not available inside a loop. This option makes <TMPL_VAR>s like global variables in PHP - they have unlimited scope. This option also affects <TMPL_IF> and <TMPL_UNLESS>. Example:
  This is a normal variable: <TMPL_VAR NORMAL>.<P>

  <TMPL_LOOP NAME=FROOT_LOOP>
     Here it is inside the loop: <TMPL_VAR NORMAL><P>
  </TMPL_LOOP>
Normally this wouldn't work as expected, since <TMPL_VAR NORMAL>'s value outside the loop is not available inside the loop.
The global_vars option also allows you to access the values of an enclosing loop within an inner loop. For example, in this loop the inner loop will have access to the value of OUTER_VAR in the correct iteration:
   <TMPL_LOOP OUTER_LOOP>
      OUTER: <TMPL_VAR OUTER_VAR>
        <TMPL_LOOP INNER_LOOP>
           INNER: <TMPL_VAR INNER_VAR>
           INSIDE OUT: <TMPL_VAR OUTER_VAR>
        </TMPL_LOOP>
   </TMPL_LOOP>
As in htmltmpl, you can use the GLOBAL attribute for one variable alone, instead of setting global_vars on. To do so, add a GLOBAL attribute to the tag, this way:
<TMPL_LOOP LOOP>
    <TMPL_VAR NAME="COUNTRY" GLOBAL="1"> <br>
    <TMPL_VAR NAME="NAME">
</TMPL_LOOP>
hash_comments
This option is not implemented in HTML::Template. Allows to insert hash comments as in htmltmpl. Hash comments are like this:
<TMPL_VAR NAME="name"> ### Three hashes and one space make a comment
The comments will be stripped away if this option is set to 1.
imark
This option is not implemented in HTML::Template. Allows to specify the initial marker for the template tags. Default value is <
emark
This option is not implemented in HTML::Template. Allows you to specify the end marker for the template tags. Default value is >
Example:
parse_html_comments
This option is not implemented in HTML::Template. Tells the parser to look for template tags inside HTML comments. If you are enclosing any of your template tags inside HTML comments for your template to be valid markup, leave this option as true. Otherwise set it to false, which will make parsing slightly faster. Default value is true. Examples:
  1.  
    • In the script:
      $options = array('filename'=>'template.tmpl',
                       'imark'=>'<', 'emark'=>'>',
                       'parse_html_comments'=>true);
    • In the template:
      <!-- TMPL_VAR name="title" --> = <TMPL_VAR name="title">
    • In the script:
      $options = array('filename'=>'template.tmpl',
                       'imark'=>'[[', 'emark'=>']]',
                       'parse_html_comments'=>true);
    • In the template:
      <!-- [[TMPL_VAR name="title"]] --> = [[TMPL_VAR name="title"]]
    • In the script:
      $options = array('filename'=>'template.tmpl',
                       'imark'=>'<[', 'emark'=>']>',
                       'parse_html_comments'=>true);
    • In the template:
      <!-- [TMPL_VAR name="title"] --> = <[TMPL_VAR name="title"]>
Note the syntax used when the initial marker begins with a < sign or when the end marker ends with a > sign. This is done so in order to preserve compatibility with existing HTML::Template templates.

Saving and loading compiled templates

To save a compiled template call the SaveCompiled($dir, $overwrite) method. The first argument is the directory name where the compiled template file will be we stored. If it is NULL or not specified the directory name of the original template file is used. The compiled template file name is the original template name with a "c" character appended. If a file with that name already exists the function exits with error, unless the $overwrite argument takes a true value (defaults to 0).

Returns the path to the compiled template. Example:

<?php
require_once("template.php");
$t =& new Template("bench3.tpl");
if ($output = $t->SaveCompiled(".")) {
    echo ("$output saved");
}
?>

If you assign variables before saving the compiled template the assigned values are stored as well.

To load a compiled template, use the LoadCompiledTemplate($filename) function with the name of the compiled template file as the argument. Once loaded proceed as usual. Example:

<?php
require_once("template.php");
$template =& LoadCompiledTemplate("mytemplate.tplc");
$template->AddParam("title", "Hellow world!");
$template->EchoOutput();
?>

Back to main index | Samples page