Tpl is a tiny PHP template engine, inspired by the hierarchical template capabilities of the Django Python framework.
Why another template engine? Because I feel that most template engines miss the point that PHP already is a template language, and attempt to replace PHP with a new syntax just for templates. This results in a massive overhead for parsing, and in most cases tends to end up a little restrictive too. In short, they attempt too much.
Instead I have created a simple library which implements the features I want and “runs” templates that are HTML with inline PHP. There are multiple benefits to this approach:
Instead of directly parsing templates, Tpl runs them through PHP with include() and relies on calls to the various Tpl hooks to denote structure. Each template is only run once per request for both performance and removing the duplication of side-effects.
Tpl is based around 4 simple hooks:
Tpl::block('name') - start a named template blockTpl::endblock() - end the current blockTpl::super() - get the value of the current block from higher up in the template hierarchyTpl::inherit() - extend from another templateIn addition to this, there are a few other assumptions/restrictions:
Tpl first runs the requested template, using the hooks to create a tree of block, super and text nodes. If there was a call to Tpl::inherit(), the same action is applied to the parent template, and this happens recursively until a template doesn’t inherit from anything (the root template).
At this point, we have a tree representing each template. The next step is to replace the calls to Tpl::super() with the block node strings from further up the tree. The string value of a node is the concatenation of the string values of its children. These values are propagated down through the hierarchy, replaced when they get overridden, until the requested template has been processed.
The final step is to “compile” the template. This involves propagating “final” block values from the bottom of the template tree back to the root. The final output of parsing the template is the root template with all block substitutions completed, etc.