
Originally Posted by
Gaheris
Well yes, I would guess that the template 'engine' consists more or less of a
eval call.
I would have to disagree wtih you. Eval is known to be a bit slow, so that would be a pretty awful waste. I wrote a simple template engine that I'll share, that does what I need anyway (no where near the sophystication of Smarty, but I don't need Smarty or I'd use it. This templating engine is blazing fast for the basics).
It supports variables, and it supports a tag displaying another template. I use this on all my sites. 
template.php:
PHP Code:
<?php
class Template
{
var $template;
function Template($name)
{
$sql = mysql_query("SELECT * FROM template WHERE tpl_name='$name'");
if(mysql_num_rows($sql) == 0) die("Invalid Template (".$name.") Selected");
while($row = mysql_fetch_object($sql))
{
$this->template = $row->template;
}
}
function assign($tag, $old)
{
$this->template = str_replace("{".$tag."}", $old, $this->template);
}
function parse($tag, $class)
{
$this->template = str_replace("{".$tag."}", $class->template, $this->template);
}
function display()
{
echo $this->template;
}
}
?>
Tpl.php:
PHP Code:
class TPL{
var $tpl;
var $start;
var $stop;
function TPL($template = 'layout.html')
{
$this->tpl = new Template($template);
}
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
function compare()
{
return $this->stop - $this->start;
}
function pageStart($title = "")
{
$this->tpl->assign("TITLE", $title);
ob_start();
}
function pageFinish()
{
$content = ob_get_contents();
ob_end_clean();
$this->tpl->assign("CONTENT", $content);
$this->stop = $this->getmicrotime();
if ($_GET['debug'] == 1)
{
$debug = "[ Queries: ".$DB->querycount." | Execution Time: ".$this->compare()." ]";
$this->tpl->assign("DEBUG", $debug);
}
else
{
$this->tpl->assign("DEBUG", "");
}
echo $this->tpl->display();
}
}
Then a quick example would be:
PHP Code:
<?php
require("tpl.php");
$tpl = new Tpl("layout.html");
$tpl->pageStart("Test Page");
?>
Content..
<?php
$tpl->pageFinish();
?>
And if you had a links.html, you could parse {LINKS} with another function in tpl.php. Pretty straight forward templating systme, and quick as a bee.
Thoguth I'd share this.
Regards,
Nathan Wong
P.S. If anybody needs an explination, I'd be happy to explain. 
[ Edit: Ignore $DB, my bad, it's a MySQL abstration layer I use and I guess I use it on all my pages too...
]
Bookmarks