Location: PHPKode > scripts > SmashTemplate > template.php
<?php

/*

SmashTemplate

A very simple template class. It loads a template from
a file, converts placeholders into php code, then
evaluates the code. Replacing variables in this manner
allows for the usage of php code in the template. This
makes templates more flexible.

*/

class template
{
	var $contents; // holds the contents of the loaded template
	var $variables = array(); // holds set variables
	var $templatedir; // the directory containing templates.

// Sets template directory

	function template($templatedir)
	{
		$templatedir = realpath($templatedir);
		$this->templatedir = $templatedir;
	}
	
// Gets a template and stores it in the contents variable
	
	function get($filename)
	{
		$file = $this->templatedir . '/' . $filename; // creates proper filename for fopen
		$fp = fopen($file, 'r'); // opens file
		$contents = fread($fp, filesize($file) ); // reads to end of file
		fclose($fp); // closes file
		$this->contents = $contents; // stores contents of file in class variable
	}
	
// Sets a variable and adds it to the set of variables
	
	function set($variable, $value)
	{
		$this->variables[$variable] = $value;
	}
	
// Goes through template contents and replaces variables.
	
	function parse()
	{
		$template = $this->contents;
		foreach ($this->variables as $var=>$value)
		{
			$template = str_replace('<$'.$var.'$>', '<?=$'.$var.'?>', $template); // converts variable placeholder into php echo shorthand
		}
		$this->contents = $template;
	}
	
// Prints contents of template
	
	function display()
	{
		$this->parse(); // just in case
		extract($this->variables); // makes variables available for use
		eval('?>'. $this->contents); // exits php and evaluates contents of template
	}
	
}

?>
Return current item: SmashTemplate