All pastes #552265 Raw Edit

Someone

public text v1 · immutable
·published 2007-06-09 05:58 UTC
rendered paste body
<?php

class Template
{
	public $language;
	private $variables = array();
	
	public function __construct($language = 'en-us')
	{
		$this->loadLang($language); 
	}
	
	public function parse($template_file)
	{
		if(!file_exists($template_file)) throw new Exception("Template: {$template_file} does not exist.");
		if(!$template_buffer = file_get_contents($template_file)) throw new Exception("Cannot read template {$template_file}.");
		
		$template_buffer = preg_replace('~{\$(.*)}~U', '<?php echo $this->getVar("$1"); ?>', $template_buffer);
		$template_buffer = preg_replace('~{\@(.*)}~U', '<?php echo $this->getText("$1"); ?>', $template_buffer);
		
		$tag_array = preg_split("~<(/?)tpl:([^>]*)>~", $template_buffer, -1, PREG_SPLIT_DELIM_CAPTURE);
		
		$node_stack = array();
		
		for($i = 0; $i < count($tag_array); $i++) {
			switch($i % 3) {
				case 0:
					# Text
					break;
				case 1 || 2:
					$tag_parts = preg_split("~([^\W]*)(=(\"|')?([a-z0-9\s.-_]*)(\"|')?)~i", $tag_array[$i + 1], -1, PREG_SPLIT_DELIM_CAPTURE);
					$tag_name = trim(strtolower($tag_parts[0]));
					for($i = 1; $i < count($tag_parts); $i += 6) {
						$tag_args[$tag_parts[$i]] = $tag_parts[$i + 3];
					}
					
					if($tag_array[$i] != '/') {
						$node = array_pop($node_stack);
						$last_node = end($node_stack);
					} else {
						$node = array_pop($node_stack);
					}
					
					$i++;
					break;
				default:
					throw new Exception("WTF?");
					break;
			}
		}
		return $template_buffer;
	}
	
	public function render($file)
	{
		$template_file = "templates/{$file}";
		$cache_file = "cache/{$file}";
		if(file_exists($cache_file) && filemtime($cache_file) > filemtime($template_file)) {
			require_once($cache_file);
		} else {
			$template_buffer = $this->parse($template_file);
			$this->cache($cache_file, $template_buffer);
			require_once($cache_file);
		}
	}
	
	public function cache($cache_file, $template_buffer)
	{
		$cache_file = fopen($cache_file, 'w');
		fwrite($cache_file, $template_buffer);
		fclose($cache_file);
	}
	
	private function getVar($variable) 
	{
		return ($this->variables[$variable]) ? $this->variables[$variable] : '{$' . $variable . '}';
	}
	
	private function getText($text)
	{
		return ($this->language[$text]) ? $this->language[$text] : $text;
	}
	
	private function loadLang($language)
	{
		$language_file = "locale/{$language}.php";
		if(!file_exists($language_file)) throw new Exception("Language: {$language} can not be loaded.");
		require_once($language_file);
	}
	
	public function __set($variable, $value)
	{
		$this->set($variable, $value);
	}
	
	public function set($variable, $value)
	{
		$this->variables[$variable] = $value;
	}
}


$Template = new Template();

$Template->set('title', 'Template Test Page');
$Template->hello = "Andrew";
$Template->lol = "k4st says...";

$Template->render('index.html');

?>