View Single Post
Old 12-21-2007, 07:13 PM   #3 (permalink)
Tanax
The Prestige
Upcoming Programmer Inquisitive 
 
Tanax's Avatar
 
Join Date: Sep 2007
Location: Sweden, Stockholm
Posts: 1,080
Thanks: 115
Tanax is on a distinguished road
Default

Quote:
Originally Posted by sjaq View Post
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($fbfilesize(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)
Wow, thanks!! I will study the code more carefully :D

Also one thing, does this also work with variables?
Like if I do:

Code:
You are currently on page {page}
And that would be replaced with the value of
PHP Code:
$page 
???

THanks once again :)
Tanax is offline  
Reply With Quote