Here is an easy templating class I wrote. First I'll give you the example useage:
template file: "path/to/template.extension"
Template placeholders should be uppercase and wrapped in {}
Code:
<h2>Hello, <strong>{YOUR_NAME}</strong>!</h2>
<p>My name is <em>{MY_NAME}.</em></p>
Example useage
PHP Code:
<?php
require_once('class.TreeTemplate.php');
// instance the class and pass in a template
// containing html and 'marker' tags
$template = new TreeTemplate('path/to/template.extension');
// Replaces {YOUR_NAME} in the template with $your_name
$your_name = 'Karl';
$template->assignValues('YOUR_NAME', $your_name);
// Replaces {MY_NAME} in the template with $my_name
// Case doesn't matter in assignValues, the token is
// passed through strtoupper()
$my_name = 'Tree';
$template->assignValues('mY_Name', $my_name);
// This method does the replacements
// the optional parameter tells the class if
// it should remove non-substituted tokens or not
$template->parseTemplate(true);
// echo's the template
$template->echoTemplate();
?>
The above script would output:
Hello, Karl!
My name is Tree.
Class file: class.TreeTemplate.php
PHP Code:
class TreeTemplate
{
/**
* Template path and filename
*
* @access private
* @var string
*/
var $TEMPLATE = '';
/**
* Contents of $this->TEMPLATE
*
* @access private
* @var string
*/
var $CONTENT = '';
/**
* Values to replace in $this->CONTENT
*
* @access private
* @var array
*/
var $VALUES = '';
/**
* Array of possible errors
*
* @access private
* @var array
*/
var $ERR = array();
/**
* Constructor function. Pass it the html template you wish to use
*
* @access public
* @param string $tpl Template path and file. Absolute or relative from the current location in the file system, not webroot
* @return TreeTemplate
*/
function TreeTemplate($tpl)
{
/**
* Is $tpl a file and can we read it?
*/
if(file_exists($tpl) && is_readable($tpl))
{
$this->TEMPLATE = $tpl;
$this->CONTENT = file_get_contents($this->TEMPLATE);
}
else
{
trigger_error(get_class($this).'::'.__FUNCTION__.'() '.$tpl .' is not a valid file', E_USER_ERROR);
}
}
/**
* Assigns a new template and overwrites the previous one
*
* @access public
* @param string $tpl Template path and file. Absolute or relative from the current location in the file system, not webroot
* @return boolean True on success, False on failure. Call TreeTemplate->lastError(); for the error message
*/
function changeTemplate($tpl)
{
/**
* Is $tpl a file and can we read it?
*/
if(file_exists($tpl) && is_readable($tpl))
{
$this->TEMPLATE = $tpl;
$this->CONTENT = file_get_contents($this->TEMPLATE);
return true;
}
else
{
$this->ERR[] = get_class($this).'::'.__FUNCTION__.'() '. $tpl .' is not a valid file';
trigger_error($this->lastError(), E_USER_WARNING);
return false;
}
}
/**
* Assigns data to the template markers
*
* @access public
* @param string $key The name of the token used as a placeholder in the template. **without {}
* @param string $html Data to replace $key with
*/
function assignValues($key, $html)
{
$this->VALUES[$key] = $html;
}
/**
* Replaces the placeholding tokens with the data assigned in $this->assignValues
*
* @param boolean[optional] $removeEmpty Should we remove any tokens that are not used?
* @return boolean True on success, False on failure. Call TreeTemplate->lastError(); for the error message
*/
function parseTemplate($removeEmpty = false)
{
if($this->CONTENT == '')
{
$this->ERR[] = get_class($this).'::'.__FUNCTION__.'() Error retrieving '.$this->TEMPLATE;
trigger_error($this->lastError(), E_USER_WARNING);
return false;
}
else
{
if(is_array($this->VALUES))
{
foreach($this->VALUES as $token => $html)
{
$this->CONTENT = str_replace('{'.strtoupper($token).'}', $html, $this->CONTENT);
}
if($removeEmpty)
{
if(false === $this->removeEmpty())
{
return false;
}
}
return true;
}
else
{
$this->ERR[] = get_class($this).'::'.__FUNCTION__.'() $this->VALUES is empty or not an array';
trigger_error($this->lastError(), E_USER_NOTICE);
return false;
}
}
}
/**
* Removes empty tokens from the template
*
* This method is called in TreeTemplate::parseTemplate(). There is no need to
* call it yourself although it won't hurt anything.
*
* @access public
* @return boolean True on success, False on failure. Call TreeTemplate->lastError(); for the error message
*/
function removeEmpty()
{
if($this->CONTENT == '')
{
$this->ERR[] = get_class($this).'::'.__FUNCTION__.'() Error retrieving '.$this->TEMPLATE;
trigger_error($this->lastError(), E_USER_WARNING);
return false;
}
else
{
// Replace any {TOKEN} items with an empty string
$this->CONTENT = preg_replace("/({[A-Z0-9_]*})/", "" ,$this->CONTENT);
return true;
}
}
/**
* Returns the completed template. Should be called returnTemplate() or something, sorry =(
*
* @access public
* @return mixed Finished template on success, False on failure. Call TreeTemplate->lastError(); for the error message
*/
function displayTemplate()
{
if($this->CONTENT == '')
{
$this->ERR[] = get_class($this).'::'.__FUNCTION__.'() No content to display';
trigger_error($this->lastError(), E_USER_NOTICE);
return false;
}
else
{
return $this->CONTENT;
}
}
/**
* Echo's TreeTemplate::displayTemplate()
*
* I named displayTemplate() wrong but a lot of code uses it so
* I made this wraper method. displayTemplate() should be getTemplate()
* or something.
*
* @access public
*
*/
function echoTemplate()
{
echo $this->displayTemplate();
}
/**
* Gets the last error during execution
*
* @access public
* @param boolean[optional] $remove_error Should we clear this error from the error array?
* @return string The textual details of the error
*/
function lastError($remove_error = false)
{
$i = count($this->ERR)-1;
if($remove_error)
{
unset($this->ERR[$i]);
}
return $this->ERR[$i];
}
}
Bookmarks