TracNav menu
Creating templates
patTemplate allows you to split a page into several blocks, called templates. It requires you to at least specify one block that contains the complete page, the root template. Inside this template, you may nest as many templates, as you like. Each of these templates should have its unique name, so it can be addressed from your PHP application. To mark a template in your page, you need to enclose the HTML code in a <patTemplate:tmpl/> tag:
<patTemplate:tmpl name="page">
This is the main page.
<patTemplate:tmpl name="foo">
It contains another template.
</patTemplate:tmpl>
<patTemplate:tmpl name="bar">
And one more.
</patTemplate:tmpl>
</patTemplate:tmpl>
Loading this template from a file is easy:
$tmpl = new patTemplate();
$tmpl->readTemplatesFromInput('my-templates.tmpl');
patTemplate will now open the file my-templates.tmpl and scan it for <patTeamplate:tmpl/> tags. It will create a structure like this:
+ page + foo + bar
If you want to send the HTML content to the browser, you need to call the displayParsedTemplate() method and pass the name of the template to display:
$tmpl->displayParsedTemplate('page');
When parsing and displaying a template, all nested templates will be displayed as well. So calling this method will display:
This is the main page.
It contains another template.
And one more.
If you do not want to echo the HTML code, but store it in a PHP variable, you may call getParsedTemplate() instead. If you do not pass the name of a template to displayParsedTemplate() or getParsedTemplate(), patTemplate will display the root template (i.e. the first template it read after creating the patTemplate object).
Chosing a directory for your templates
You will certainly not put your template files into the root directory of your webspace, but rather in a folder called templates or something similar. If you do not want to specify the full path to the files for every call to readTemplatesFromInput() you may use the setRoot() method:
$tmpl = new patTemplate();
$tmpl->setRoot('/path/to/templates');
$tmpl->readTemplatesFromInput('my-template.tmpl');
This example will load the templates from the file /path/to/templates/my-template.tmpl.
patTemplate also allows you to read the templates not only from the file system, but virtually any data source.
Further reading
Of course, this is not all the functionality that patTemplate provides. patTemplate provides different types of templates, that come with different functionality:
- The simpleCondition template allows you to emulate an if statement.
- The condition template allows you to emulate if/else and switch/case statements.
- The modulo? template allows you to create templates to represent alternating lists.
Besides the tmpl tag there are several other tags and it is even possible to create your own tags.
