Minimalistic template engine

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

Post Reply
Gambler
Forum Contributor
Posts: 246
Joined: Thu Dec 08, 2005 7:10 pm

Minimalistic template engine

Post by Gambler »

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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

usage? code examples?
Gambler
Forum Contributor
Posts: 246
Joined: Thu Dec 08, 2005 7:10 pm

Post by Gambler »

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.
Post Reply