Skip to content

PHP Template System

von dennis

Hier mal ein Anfang für ein eigenes Template-System für PHP:

Ein Beispiel für die index.tpl:

[head.tpl]
        <div id="content">
                <p>your content here</p>
        </div>
[footer.tpl]

Die Dateien head.tpl und footer.tpl können weitere Template-Dateien enthalten. Es wird rekursiv geparst.

Der Aufruf:

echo new Template('index.tpl');

Die Klasse:

class Template {
        private $template;
 
        public function __construct($templateFile) {
                if (is_file($templateFile)) {
                        $this->template = file_get_contents($templateFile);
                } else {
                        die('Template File "'.$templateFile.'" not found.');
                } 
        }
 
        private function getModules($s) {
                preg_match_all( "/\[(.+?)\]/is", $s, $matches);
                return $matches[1];
        }
 
        private function parse($tpl) {
                $modules = $this->getModules($tpl);
                if (count($modules)) {
                        foreach ($modules as $mod) {
                                if (is_file($mod)) {
                                        $tpl = str_replace('['.$mod.']',file_get_contents($mod), $tpl);
                                        $tpl = $this->parse($tpl);
                                } 
                        }
                }
                return $tpl;
        }
 
        public function __toString() {
                return $this->parse($this->template);
        }
 
 
}

Aus → PHP

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS

*