Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.
Moderator: General Moderators
Gambler
Forum Contributor
Posts: 246 Joined: Thu Dec 08, 2005 7:10 pm
Post
by Gambler » Fri May 26, 2006 1:41 pm
Code: Select all
<?php
class Template{
static private $path2function = array();
private static function load($path){
$code = file_get_contents($path);
$name = create_function('$_', "?>$code<?php ");
self::$path2function[$path] = $name;
}
static function show($path, $info = array()){
$path = "templates/$path.inc";
if (!isset(self::$path2function[$path])) { self::load($path); }
$name = self::$path2function[$path];
if (function_exists($name)) {
$name($info);
} else {
throw new Exception("Template function is not avalabale");
}
}
static function get($path, $info = array()){
ob_start();
self::show($path, $info);
$block = ob_get_contents();
ob_end_clean();
return $block;
}
}
?>
Last edited by
Gambler on Fri May 26, 2006 4:01 pm, edited 2 times in total.
Gambler
Forum Contributor
Posts: 246 Joined: Thu Dec 08, 2005 7:10 pm
Post
by Gambler » Fri May 26, 2006 3:55 pm
Usage:
Code: Select all
<?php
Template::show('article/plain', array('text' => 'tihs is my text', 'title' => 'The Article'));
?>
get works in the same way, but it returns output instead of echo'ing it.
Template file:
templates/article/plain.inc
Code: Select all
<h2><?=$_['title']?></h2>
<?=$_['text']?>
Templates are converted into functions, which is very efficient. You can nest and loop all you want. On the other hand, template files are pure php. There is no boilerplate code whatsoever. Can be as simple as you want and as powerful as you want.