Templates functions
Index
These functions allow you to process HTML template files in a very fast and efficent way.
You can find the project's homepage at http://php-templates.sourceforge.net/.
Templates are generally used in projects with so-called N-tier architecture to separate presentation and business logic layers. When using templates you have all web site's design in .html files which are processed (parsed) by your .php scripts. Benefits of this tecnology are obvious:
We all do realize that there are many other template solutions on the market of N-tier architecture projects and php_templates is just the one of them. However, when we're going to compare php_templates to other projects we will find some differencies:
What you will NOT find in php_templates is any kind of scripting language to be used in a template. As it was stated above, templates are used to separade code from design. That is why any logic inside of a template goes strictly against templates ideology. However, almost any web developers community keeps endless discussions about whether to use some programming inside of a template or not. That is really going to be a sort of religious war. Nevertheless, there are many projects with their own scripting languages to be used in templates, and you may always switch to them. They aren't too fast though.
Instead of starting with a "Hello, World!" example, let's take some real life task: a list of prices taken from a database.
Product names and their respective prices are kept in a database table with fields product and price. What we have to do is just to generate a web page with all prices. First, we are going to prepare a template file prices.html:
<html>
<head>
<title>Prices of ACME, Inc.</title>
</head>
<body>
<table border=1 cellspacing=0 cellpadding=2>
<tr>
<th>Product</th><th>Price</th>
</tr>
<tmpl:row>
<tr>
<td>{product}</td><td>{price}</td>
</tr>
</tmpl:row>
</table>
</body>
</html>
Some parts of the template are marked bold. These are not HTML, but php_templates tags.
<tmpl:row> is where a template context named row begins, and </tmpl:row> is where the context ends. A template context is a dynamic block in a template which could be repeated zero or more times. This process is called iteration.
{product} and {price} are just template tags. Template engine replaces its tags with values provided by PHP code.
If we looked at this HTML page in a browser we would just see a table with two rows in it. That doesn't look like a price list, does it? Now let's do some magic and complete our task. We need some PHP code to process the template and here it goes:
<?php
/* MySQL DB connection code is skiped */
$template = tmpl_open('prices.html');
$sql = 'SELECT product, price FROM Products ORDER BY product';
$result = mysql_query($sql) or die('SQL error: '.mysql_error());
while($data = mysql_fetch_assoc($result)) {
tmpl_iterate($template, 'row');
tmpl_set($template, 'row', $data);
}
echo tmpl_parse($template);
?>
First, we tell to the php_templates engine what template file we are going to use. This is done by tmpl_open() function.
Next, we execute an SQL query to get the data from database.
After the SQL query is done we start the loop where all magic is being done. tmpl_iterate() creates new iteration of the context row, and tmpl_set() assigns values from $data['product'] and $data['price'] (obtained from the database) to their respective template tags in a newly iterated context.
When the template is loaded with data we parse it with tmpl_parse() function and print the parsed template content to output.
Nothing else. That was easy, wasn't it?
In order to have these functions available, you must compile PHP with Templates support.
Download the source code into the ext/ directory of PHP source distribution. Unpack the archive. The <PHP_source>/ext/templates/ directory should appear. Change back to the main PHP source directory and rebuild the PHP configuration script:
cd <PHP_source_dir>
./buildconf
Now, when configuration script is regenerated, you may configure PHP enabling Templates functions and proceed with usual compiling and installation operations:
./configure <your-PHP-settings> --enable-templates
make
make install
Download the source code and unpack it into any directory. Now run the following commands:
cd templates
phpize
./configure --enable-templates=shared
make
When everything is done you will find a templates.so file in the modules/ directory. This is the compiled loadable Templates module. Copy it to the same directory where your script is and use the following PHP code to load the module:
<? if(!extension_loaded('templates')) dl('php_templates'); ?>
Thanks to Noor Dawod for writing this section.
I don't know why there are plenty of errors while compiling the source code under FreeBSD (maybe other BSD's, though not important now), but the truth is that I found a fast way to compile it with no errors.
This is done by using the Ports collection without the need to compile and install Apache. The steps to compile php-templates is as follows:
$ su -
Password: <root pass here to become root>
# cd /usr/ports/www/php-templates
# cat distinfo
This will list the contents of the "distinfo" file. It'll look something like this:
MD5 (php_templates-1.1.tar.gz) = e7c30fd006f2a63862fdc40b76757f5f
Note that FreeBSD's ports collection as of 4.7-STABLE is not still updated with the latest version of php-templates. What we need to do is change the version number and compile without MD5 checksum, like this:
# replace php_templates-1.1.tar.gz php_templates-1.4.tar.gz -- distinfo
# vi Makefile
<change the line PORTVERSION= to reflect the version you're compiling>
Now, we're ready. Do the last thing:
# make NO_CHECKSUM=yes
This would download and compile the php-templates in no time. After that, you'll have a compiled extension named templates.so residing in /usr/ports/www/php-templates/work/templates/modules.
Now you can copy the extension file to the extension_dir defined for your PHP version (normally in php.ini) and add the following line in php.ini:
extension=templates.so
Remember to clean the php-templates compilation directory using:
# make clean
Also, if you're already running Apache or other web server, remember to restart it for things to make effect.
Closes an open template handle.
Synopsis
bool tmpl_close( int template )
Return value
Returns TRUE on success and FALSE on failure
Description
The template pointed to by tmpl is closed.
The template handle tmpl must be valid, and successfully created by tmpl_open() or tmpl_load().
Changes the current context in a template and/or returns path to the current context.
Synopsis
string tmpl_context( int template [, string path ] )
Return value
Returns global path to currently active template context.
Description
Template contexts are like directories in a file system, and tmpl_context() function is like a chdir command that you use in a command line shell.
Every template context has its path from the root context which is a template itself.
When passing a path parameter to any template function you may do that in both global (like '/context1/context2/tag') and local ('context2/tag' or '../context/tag') forms. You may not have two contexts with the same global path!
Note, that a call to tmpl_context() on a context which is empty (without any template tags assigned in it) and not iterated, creates a new iteration of the given context!
Example
<!-- template.html -->
<table border=1 cellspacing=0 cellpadding=2>
<tmpl:row><tr>
<td>{cell}</td>
</tr></tmpl:row>
</table>
<?php /* template.php */
$template = tmpl_open('template.html');
tmpl_context($template, 'row');
for($i=0; $i < 10; $i++) {
tmpl_iterate($template, '/row');
tmpl_set($template, 'cell', $i);
}
echo tmpl_parse($template);
?>
Returns the value of a tag or a context in the last iteration.
Synopsis
mixed tmpl_get( int template, string path )
Return value
When path points to a tag, the function returns tag's value in the last iteration of its context.
When a context is addressed by path, the returned value is an array containing all values of tags and context within the the given context.
Returns FALSE on failure.
Iterates a context.
Synopsis
bool tmpl_iterate( int template, string path )
Return value
Returns TRUE on success, and FALSE on failure.
Description
This function iterates a context pointed to by path.
By default empty contexts (which have no any tags assigned in them) are not parsed by tmpl_parse() function. If you want an empty context to appear on the page, it needs to be iterated. Every subsequent iteration of an empty context gives no result.
Loads a template from a string.
Synopsis
int tmpl_load( string template [, array config ] )
Return value
Returns newly created template handle or FALSE on error.
Description
Acts exactly like tmpl_open(), but instead of a filename with template, loads a template from template parameter.
See also
tmpl_open()
Loads a template from file.
Synopsis
int tmpl_open( string filename [, array config ] )
Return value
Returns newly created template handle or FALSE on error.
Description
This function loads a template from filename file. If allow_url_fopen option is enabled in your php.ini file, you may load templates from remote sites (see manual on fopen() function).
When the second parameter s passed to the tmpl_open() function, the engine reads the following configuration parameters from config array:
left - a string with left part
of template tag
right - right part of template tag
ctx_ol - left part of template context opening tag
("context open left")
ctx_or - right part of template context opening
tag ("context open right")
ctx_cl - left part of template context closing tag
("context close left")
ctx_cr - right part of template context closing
tag ("context close right")
Only ctx_cr parameter may be left blank. In this case whole context closing tag should be assigned to ctx_cl configuration parameter. This is done to support templates made in Macromedia® Dreamweaver® visual HTML-editor.
The following is the default configuration of php_templates engine:
$config = array(
'left' => '{',
'right' => '}',
'ctx_ol' => '<tmpl:',
'ctx_or' => '>',
'ctx_cl' => '</tmpl:',
'ctx_cr' => '>'
);
Also, every template may have its own configuration given in an HTML tag <template>:
<template left="{" right="}" ctx_ol="<tmpl:" ctx_or=">" ctx_cl="</tmpl:" ctx_cr=">">
Example
The following example opens Macromedia® Dreamweaver® template:
$template = tmpl_open('template.html', array(
'ctx_ol' => '<!-- TemplateBeginEditable name="',
'ctx_or' => '" -->',
'ctx_cl' => '<!-- TemplateEndEditable -->",
'ctx_cr' => ''
));
Parses a template.
Synopsis
string tmpl_parse( int template [, string path ] )
Return value
Returns parsed template content or FALSE on error.
Description
When you finished assigning values to template tags and contexts, you call tmpl_parse() to parse the loaded template and take the resulting content.
The second optional parameter path points to a context to be parsed. In this case only the addressed context is parsed.
You may call tmpl_parse() on a template as many times as you need.
Assigns a value to a template tag.
Synopsis
bool tmpl_set( int template, string
path, mixed value )
bool tmpl_set( int template, array values )
Return value
Returns TRUE on success, or FALSE on failure.
Description
template is a template handle which is obtained by a tmpl_open() or tmpl_load() function call.
path is a global or local path of a tag or context to receive values. This parameter should point to a template context when the value is an array. Associative arrays provide values for tags named by array keys. Indexed arrays with subarrays in values create new iterations of the context pointed to by path.
When called with two parameters, the path is assumed to be the current path in the template (see tmpl_context()).
Template handle can be passed as a value too. In this case template is parsed and its resulting output is assigned to the tag.
See also
tmpl_context(), tmpl_iterate()
Assigns a value to a tag with the same name in every context
Synopsis
bool tmpl_set_global( int template, string tag, string value )
Return value
Returns TRUE on success, or FALSE on failure.
Description
When called every tag named by tag parameter is assigned the value in every context of template.
Retrieves template's structure.
Synopsis
array tmpl_structure( int template [, string path [, int mask [, int mode ] ] ] )
Return value
Returns array with template tags and contexts hierarchy.
Description
This function is useful when program doesn't know what template tags are present in template, and the code may depend on what tags are used in the template.
template is a valid template handle obtained by tmpl_open() or tmpl_load() function call.
path is a global or local path pointing to a context which structure is to be retrieved. The current path is used when this parameter is omitted.
mask parameter filters the function's output by elements type. It could be set to one of three values:
mode parameter changes the structure of resulting array and could take one of the following values:
TMPL_LONG - retrieve full path to every template element. Context paths are terminated with a slash (/) character and tag paths are not. This is the default value.
TMPL_SHORT - only get a tag or a context name without full path to the root context.
Checks type of template element.
Synopsis
int tmpl_type_of( int template, string path )
Return value
Returns TMPL_TAG when path is pointing to a tag, and TMPL_CONTEXT when a context is pointed to by path.
Returns FALSE when given path doesn't exist in the template.
Unassignes a value from a tag or empties a context.
Synopsis
bool tmpl_unset( int template, string path )
Return value
Returns TRUE on success, or FALSE on failure.
Description
Deletes the value assigned to the tag pointed by path in the current iteration or deletes iterations of a context.