PHPTAL
Dies ist die Hauptklasse der Bibliothek.
Ihre gebräuchlichste Verwendung:
<?php
// include the library
require_once 'PHPTAL.php';
// instantiate a new PHPTAL object using specified template file
$tpl = new PHPTAL('mytemplate.xhtml');
// setting some template context variables
$tpl->title = 'my title';
$tpl->values = array(1,2,3,4);
$tpl->user = new User('Joe');
// execute the template and echo the result in a 'secure' way
try{
echo $tpl->execute();
}
catch (Exception $e){
echo "Exception thrown while processing template\n";
echo $e;
}
?>
You can perfectly well choose to specify the template source after setting context variables.
<?php
…
$tpl = new PHPTAL();
// it is a matter of taste but you can use the set() method instead of
// setting context using PHPTAL::__set() like above
$tpl->set('title', 'my title');
$tpl->set('values', array(1,2,3,4));
$tpl->set('user', new User('Joe'));
$tpl->setTemplate('mytemplate.xhtml');
…
?>
You can also decide to use a generated string as the template source instead of using an existing template file:
<?php
$src = <<<EOS
<html>
<head>
<title tal:content="title">my title</title>
</head>
<body>
<h1 tal:content="title">my title</h1>
</body>
</html>
EOS;
require_once 'PHPTAL.php';
$tpl = new PHPTAL();
$tpl->setSource($src);
$tpl->title = 'this is my title';
try {
echo $tpl->execute();
}
catch (Exception $e){
echo $e;
}
?>
In the above example, because PHPTAL requires a template source identifier (usually the template file realpath), PHPTAL will use the md5 of the $src
parameter as a unique identifier. You may decide to force the identifier using a second setSource()
argument:
<?php
$src = <<<EOS
<html>
<head>
<title tal:content="title">my title</title>
</head>
<body>
<h1 tal:content="title">my title</h1>
</body>
</html>
EOS;
require_once 'PHPTAL.php';
$tpl = new PHPTAL();
// If you specify where the source comes from (second argument to setSource),
// PHPTAL will be able to generate more helpful error messages.
$tpl->setSource($src, __FILE__);
$tpl->title = 'this is my title';
try {
echo $tpl->execute();
}
catch (Exception $e){
echo $e;
}
?>