PHP Template Engine
I have a fairly simple template engine in PHP:
<?php
define("PATH","http://".$_SERVER['HTTP_HOST']."/templater");
class Templater{
private $title;
private $path;
private $copyright = '©2011 Все права защищенны';
private $date;
private $time;
public function tmp($title,$path=NULL){
$this->title = $title;
$this->path = $path;
$this->date = date("d.m.Y");
$this->time = date('H:i:s');
$tmp = file_get_contents(PATH.'/tmp/'.$this->path);
$tmp = str_replace('{TITLE}',$this->title,$tmp);
$tmp = str_replace('{DATE}',$this->date,$tmp);
$tmp = str_replace('{TIME}',$this->time,$tmp);
$tmp = str_replace('{COPYRIGHT}',$this->copyright,$tmp);
return $tmp;
}
}
$templater = new Templater();
?>
What a file index.php and where it is necessary already in the root of the site, I do the following:
require_once 'class/templater.php';
print $templater->tmp($title,'header.tpl');
print $templater->tmp($title,'body.tpl');
print $templater->tmp($title,'footer.tpl');
To call the template itself.
I need to be able to use php code in tpl files, for example
[if()] [/if] [elseif()] [/elseif] [else] [/else] [while ()] [/while] [for()] [/for] [include file=""] [require file=""] [switch ()] [/switch]
Well, here is the similarity, at least as the main thing that if the file was tpl and you could use php code in it, I would be very grateful as I have been tormented by the search for several days, please do not offer smarty and other template engines...
1 answers
When using file_get_contents to execute php constructs, you will need to add the logic for replacing php-like commands in templates. In one of my developments, I solved this problem by sending all the variables to the template engine and accessing the class objects directly in the templates.
Template Engine code:
class Templater{
function __construct(){}
public function AddVariant($var,$name) {
$this->$name = $var;
}
public function Template($TplFile) {
require_once $TplFile;
}
}
Sending variables to the template engine:
//Инициализируем шаблонизатор
$templater = new Templater();
//Отправляем шаблонизатору переменные
$templater->AddVariant($Content->header, 'header');
$templater->AddVariant($Content->text, 'text');
//Назначаем файл-шаблон
$templater->Template($tpl);
Code (sample) of the page template
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $this->header['title']; ?></title>
<meta name="description" content="<?php echo $this->header['meta_d']; ?>" />
<meta name="keywords" content="<?php echo $this->header['meta_k']; ?>" />
</head>
<body>
<?php echo $this->text; ?>
</body>
</html>
Another bike that doesn't claim to be perfect, but I hope it will help Help you develop your skills.