Posted By

ratzo on 01/15/11


Tagged

class template


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jirimelcak


Template class


 / Published in: PHP
 

Please, feel free to suggest improvements

  1. <?php
  2.  
  3. class Template {
  4.  
  5. /*
  6. * Array containing the variables to be used inside the template
  7. */
  8. protected $properties = array();
  9.  
  10. /*
  11. * Absolute path to views directory
  12. */
  13. protected $view_path;
  14.  
  15. /*
  16. * Stores a variable to use inside a template
  17. *
  18. * @param string $name The name of the variable to use inside of the template
  19. * @param string $value The value of the variable
  20. */
  21. public function set($name, $value = null) {
  22.  
  23. if (is_array($name)) {
  24.  
  25. foreach ($name as $key => $value) {
  26.  
  27. $this->properties[$key] = $value;
  28.  
  29. }
  30.  
  31. } else { $this->properties[$name] = $value; }
  32.  
  33. }
  34.  
  35. /*
  36. * Renders the given template
  37. *
  38. * @param string $template The name of the template to render
  39. */
  40. public function render($template) {
  41.  
  42. $file = $this->view_path . $template . '.tpl';
  43.  
  44. if (file_exists($file)) {
  45.  
  46. foreach ($this->properties as $key => $value) { $$key = $value; }
  47.  
  48. include($file);
  49. $content = ob_get_contents();
  50.  
  51. echo $content;
  52. exit();
  53.  
  54. } else { die('The template file does not exists'); }
  55.  
  56. }
  57.  
  58. }
  59.  
  60. ?>

Report this snippet  

You need to login to post a comment.