trollolodn

#php #template-engine

Mar 19th, 2013
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. *** index.php ***
  2. <?php
  3.  
  4. include 'template.php';
  5.  
  6. $template = new Template();
  7. $template->assign('username', 'Vuong');
  8. $template->assign('age', '20');
  9. $template->assign('favorite', 'KFC Chicken');
  10. $template->render('myTemplate');
  11.  
  12.  ?>
  13.  
  14. *** template.php ***
  15. <?php
  16.  
  17. class Template
  18. {
  19.     private $vars = array();
  20.  
  21.     public function assign($key, $value){
  22.         $this->vars[$key] = $value;
  23.     }
  24.  
  25.     public function render($template_name){
  26.         $path = $template_name . '.html';
  27.  
  28.         if(file_exists($path)){
  29.             $contents = file_get_contents($path);
  30.            
  31.             foreach ($this->vars as $key => $value) {
  32.                 $contents = preg_replace('/\['. $key .'\]/', $value, $contents);
  33.             }
  34.  
  35.             $contents = preg_replace('/\<\!\-\- if (.*) \-\-\>/', '<?php if ($1) : ?>', $contents);
  36.             $contents = preg_replace('/\<\!\-\- else \-\-\>/', '<?php else : ?>', $contents);
  37.             $contents = preg_replace('/\<\!\-\- endif \-\-\>/', '<?php endif; ?>', $contents);
  38.  
  39.             eval(' ?>'. $contents . '<?php ');
  40.         } else{
  41.             exit("Cannot find template $path");
  42.         }
  43.     }
  44. }
  45.  
  46.  ?>
  47.  
  48. *** myTemplate.html ***
  49. Hello, [username] is [age] years old and is favourite food is [favorite]!<br/><br/>
  50.  
  51. <!-- if 1 == 1 -->
  52.     true
  53. <!-- else -->
  54.     false
  55. <!-- endif -->
Advertisement
Add Comment
Please, Sign In to add comment