trollolodn icon

#php #template-engine

trollolodn | PRO | 03/19/13 09:44:17 AM UTC | 0 ⭐ | 118 👁️ | Never ⏰ | []
PHP |

1.21 KB

|

None

|

0 👍

/

0 👎

*** index.php ***
<?php 
 
include 'template.php';
 
$template = new Template();
$template->assign('username', 'Vuong');
$template->assign('age', '20');
$template->assign('favorite', 'KFC Chicken');
$template->render('myTemplate');
 
 ?>
 
*** template.php ***
<?php 
 
class Template
{
    private $vars = array();
 
    public function assign($key, $value){
        $this->vars[$key] = $value;
    }
 
    public function render($template_name){
        $path = $template_name . '.html';
 
        if(file_exists($path)){
            $contents = file_get_contents($path);
            
            foreach ($this->vars as $key => $value) {
                $contents = preg_replace('/\['. $key .'\]/', $value, $contents);
            }
 
            $contents = preg_replace('/\<\!\-\- if (.*) \-\-\>/', '<?php if ($1) : ?>', $contents);
            $contents = preg_replace('/\<\!\-\- else \-\-\>/', '<?php else : ?>', $contents);
            $contents = preg_replace('/\<\!\-\- endif \-\-\>/', '<?php endif; ?>', $contents);
 
            eval(' ?>'. $contents . '<?php ');
        } else{
            exit("Cannot find template $path");
        }
    }
}
 
 ?>
 
*** myTemplate.html ***
Hello, [username] is [age] years old and is favourite food is [favorite]!<br/><br/>
 
<!-- if 1 == 1 -->
    true
<!-- else -->
    false
<!-- endif -->

Comments