<?php
/*
Template Library
Created by Andrew Moyer
http://www.andrewmoyer.com/
Permission is hereby granted to use this file for any purpose as long as this header block remains
unchanged and attached to the following source code.
The primary design goal of this library was to create a light-weight template system that uses
simple markers in a standard HTML file.
Template files can be any text file, usually containing HTML or XML. Variable placeholders are
substituted out with values, and regions are extracted and output at runtime. The template files
generally should be compatible with WYSIWYG editors since the variable placeholders are just plain
text and the regions are simply HTML comments. This library can even be used on various binary
files, or plain text.
As an example, a template file ("template.html") containing:
<!--SomeRegion-->
<p>##Title## is a great website.</p>
<!--/SomeRegion-->
Can be utilized by calling:
$T = new Template('template.html');
$T->Register('Title', 'Some site name');
$T->Show('SomeRegion');
The library foregoes lots of more complex concepts such as caching and in-template logic in favor
of keeping all logic in the PHP script and allowing the coders to implement a caching mechanism of
their choice.
If you happen to use this on something, please send me feedback! :-)
*/
class Template
{
private $Debug = false;
private $Variable = Array();
private $Section = Array();
private $Raw = '';
public function __construct($html='')
{
foreach($_SERVER as $k=>$v)
$this->Register($k, $v);
if($html)
$this->Load($html);
}
public function Load($html)
{
$this->Raw .= @file_get_contents($html);
}
public function Render($section)
{
$section = strtolower($section);
if(!isset($this->Section[$section]))
{
$s = quotemeta($section);
$b = "<!--$s-->";
$e = "<!--\\/$s-->";
$regex = "/$b(.*)$e/is";
preg_match($regex,$this->Raw,$result);
$this->Section[$section] = $result[1];
}
$data = $this->Section[$section];
if(!$this->Debug)
preg_match_all("/[#]{2}([^#]+)[#]{2}/",$data,$result);
foreach($this->Variable as $k=>$v)
{
if(is_int($k))
continue;
$data = preg_replace('/[#]{2}' . $k . '[#]{2}/i',preg_replace('/\$/','\\\$',$v),$data);
}
if(!$this->Debug)
foreach($result[1] as $v)
{
$v = strtolower($v);
if(!isset($this->Variable[$v]))
$data = preg_replace('/[#]{2}' . $v . '[#]{2}/i','',$data);
}
if($this->Debug)
$data = "<!--$s-->".$data."<!--/$s-->";
return $data;
}
public function SetDebug($debug)
{
$this->Debug = $debug;
}
public function Show($section, $registerErrors = false)
{
echo($this->Render($section, $registerErrors));
}
public function Register($name, $value='')
{
if(is_array($name))
foreach($name as $k=>$v)
$this->Register($k,$v);
else
$this->Variable[strtolower($name)] = '' . $value;
}
public function __destruct()
{
}
}
?>