Manual
2. Klasa PHPTAL
Jest to główna klasa biblioteki, którą musisz użyć.
Najbardziej typowe jej użycie :
<?php
// dolaczenie biblioteki
require_once 'PHPTAL.php';
// utworzenie obiektu PHPTAL z nazwa szablonu
$tpl = new PHPTAL('mytemplate.html');
// ustawienie kilku zmiennych
$tpl->title = 'my title';
$tpl->values = array(1,2,3,4);
$tpl->user = new User('Joe');
// uruchomienie szablonu i wyswietlenie wyniku w 'bezpieczny' sposob
try {
echo $tpl->execute();
}
catch (Exception $e){
echo "Exception thrown while processing template\n";
echo $e;
}
?>
Możesz także wybrać szablon źródłowy po utworzeniu obiektu i ustawieniu zmiennych.
<?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.html');
...
?>
Możesz także zadecydować, czy użyć łańcucha znaków jako źródla szablonu zamiast istniejącego pliku z szablonem :
<?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;
}
?>
W powyższym przykładzie ze względu na fakt, iż PHPTAL wymaga identyfikatora źródła szablonu (zazwyczaj bezwględna ścieżka pliku szablonu) obliczy sumę kontrolną md5 parametru $src jako unikatowy indeytfikator. Możesz wymusić nadanie własnego idenfikatoru korzystając z drugiego parametru metody setSource() :
<?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();
// because the source is contained in this file and won't be modified unless
// this file is modified, it is 'faster' to specify __FILE__ as the unique
// source identifier, thus no md5 of $src will be done on each call.
$tpl->setSource($src, __FILE__);
$tpl->title = 'this is my title';
try {
echo $tpl->execute();
}
catch (Exception $e){
echo $e;
}
?>



