12-21-2007, 06:47 PM
|
#2 (permalink)
|
|
The Acquainted
Join Date: Nov 2007
Location: Netherlands
Posts: 113
Thanks: 11
|
I tried it a couple of different ways but this seems to work fine:
Template.php
PHP Code:
<?php
class Template { public $data; const TEMPLATE_PATH = './'; public function parse($template, array $values) { $this->data = $values; if(!file_exists(self::TEMPLATE_PATH . $template . '.php')) { die('Template file doesn\'t exist'); } else { $fb = fopen(self::TEMPLATE_PATH . $template . '.php', 'r'); $contents = fread($fb, filesize(self::TEMPLATE_PATH . $template . '.php')); fclose($fb); $replaced = preg_replace_callback('/\{([a-z0-9\.]+)\}/i', array($this, 'replace_callback'), $contents); print $replaced; } } private function replace_callback($matches) { $depth = explode('.', $matches[1]); $out = $this->data; if(count($depth) > 1) { foreach($depth as $ar) { $out = $out[$ar]; } } else { $out = $out[$depth[0]]; } return $out; } }
?>
Test.php (the template)
Code:
Hello and welcome {user.username}!
Your last visit was {user.lastvisit} here on {site.name}!
Your postcount is: {user.posts.count}!
index.php
PHP Code:
<?php
require './template.php'; $tpl = new Template; $tpl->parse('test', array( 'user' => array( 'lastvisit' => 'yesterday', 'username' => 'Sjaq', 'posts' => array('count' => 10) ), 'site' => array( 'name' => 'TalkPHP' ) ));
?>
(My indentation style is a bit inconsistent, I'm trying to adapt the BSD/Allman style)
Last edited by sjaq : 12-21-2007 at 07:04 PM.
Reason: uses fopen instead of file_get_contents now
|
|
|
|