Documentation - PHP writer
About
DOMtempl_writer is an extension of DOMtempl, that allows you to "compile" DOMtempl templates into php-soup templates.
Optionally, it can also write down all the default values, keeping the usability of uncompiled templates.
Quick start
include 'domtempl.writer.php';
Include the 'writer' file instead of regular 'domtempl.php'.
New constructor flags
DOMtempl_writer::DEBUG_TAGS
- change angular brackets to html entities in compiled output.DOMtempl_writer::SAVE_DEFAULTS
- write the 'defaults section' into compiled output.DOMtempl_writer::NO_WRITE
- do not actually write anything to disk.
New constructor argument
You can pass a directory path as third constructor argument. By default, 'templates' is used.
So,
$tpl = new DOMtempl('file.html');
becomes
$tpl = new DOMtempl_writer('file.html', DOMtempl_writer::SAVE_DEFAULTS, 'compiled_templates');
Note: adding the SAVE_DEFAULTS flag is annoying, but having 'defaults section' when you don't need one is equally annoying. So far, opting for no 'defaults section' as the default...
Defaults section
Let's say you have a template, that goes like this.
<span data-var="title">The Dog</span>
The equivalent php-soup version is this:
<span><?= $title ?></span>
But, what if no $title was set by a user? In normal DOMtempl, 'The Dog' would be the default. To workaround this problem, DOMtempl_writer can add the 'defaults section', that looks like this:
<?php if (!isset($title)) $title = 'The Dog'; ?>
Note, that those defaults will still be inaccessible to you at "run-time", so if you rely on those a lot, you should probably save them to a separate file manually, and load from it. Making it automagic is on the TODO list.
Flow changes
Other than changing the include file and the class instansiation, the rest of your usage should not be affected as DOMtempl_writer provides both ->out() and ->dump() methods, which act the same.
Both will check if the compiled template exists, and if it does, include
that.
New methods
->compile( [ $with_defaults = false ] )
Returns the template as php-soup. It's up to you to save it.
->render()
Echo the compiled template. Not really useful.
New properties
Public properties ->ident
, ->lt
and ->gt
could be used to adjust the compiled output.
->from
sets the name for the base output variable.
When set to an empty string, all top-level variables are treated as stand-alone. When set to an array name, all top-level variables are treated as members of that array.
Given this DOMtempl-ate
$tpl = new DOMtempl_writer('<div data-var="food"></div>', FRAGMENT);
and doing
$tpl->from = 'view'; $tpl->render();
returns
<div><?= $view["food"] ?></div>
while
$tpl->from = ''; $tpl->render();
returns
<div><?= $food ?></div>
No 'write' method
This is not a mistake. You either allow DOMtempl_writer
do the right thing, by simply invoking
it, either forbid the writing via the NO_WRITE
flag, run the compile()
method, and
then save the template yourself.