Templater.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <?php
  2. namespace KarmaFW\Templates;
  3. class Templater
  4. {
  5. public $tpl_dir = APP_DIR . '/templates';
  6. protected $vars = [];
  7. protected $plugins = [];
  8. function __construct($tpl_dir=null, $default_vars=[])
  9. {
  10. if (is_null($tpl_dir) && defined('TPL_DIR')) {
  11. $tpl_dir = TPL_DIR;
  12. }
  13. if (! is_null($tpl_dir)) {
  14. $this->tpl_dir = $tpl_dir;
  15. }
  16. $this->assign($default_vars);
  17. $this->addPlugin('tr', function ($param) {
  18. return gettext($param);
  19. });
  20. }
  21. public function fetch($tpl, $layout=null, $extra_vars=array())
  22. {
  23. $tpl_dirs = [];
  24. if (! is_null($this->tpl_dir) && is_dir($this->tpl_dir)) {
  25. $tpl_dirs[] = $this->tpl_dir; // user templates
  26. }
  27. if (is_dir(FW_DIR . '/templates')) {
  28. $tpl_dirs[] = FW_DIR . '/templates'; // framework templates
  29. }
  30. if (empty($tpl_dirs)) {
  31. throw new \Exception("No Templates dir", 1);
  32. }
  33. $tpl_path = false;
  34. foreach ($tpl_dirs as $tpl_dir) {
  35. $tpl_path = $tpl_dir . '/' . $tpl;
  36. if (is_file($tpl_path)) {
  37. break;
  38. }
  39. $tpl_path = null;
  40. }
  41. if (is_null($tpl_path)) {
  42. throw new \Exception("Template not found : " . $tpl, 1);
  43. }
  44. extract($this->vars);
  45. extract($extra_vars);
  46. if ($tpl_path) {
  47. ob_start();
  48. include($tpl_path);
  49. $content = ob_get_contents();
  50. ob_end_clean();
  51. } else {
  52. $content = '';
  53. }
  54. // plugins. ex: {tr:English text} ==> "Texte francais"
  55. if (! empty($this->plugins)) {
  56. foreach ($this->plugins as $prefix => $callback) {
  57. preg_match_all('/{' . $prefix . ':([^}]+)}/', $content, $regs, PREG_SET_ORDER);
  58. foreach($regs as $reg) {
  59. $replaced = $callback($reg[1]);
  60. $content = str_replace($reg[0], $replaced, $content);
  61. }
  62. }
  63. }
  64. if (empty($layout)) {
  65. return $content;
  66. } else {
  67. $content_layout = $this->fetch($layout, null, array('layout_content' => $content));
  68. return $content_layout;
  69. }
  70. }
  71. public function display($tpl, $layout=null)
  72. {
  73. echo $this->fetch($tpl, $layout);
  74. }
  75. public function assign($var_name, $var_value=null)
  76. {
  77. if (is_array($var_name)) {
  78. foreach ($var_name as $k => $v) {
  79. $this->assign($k, $v);
  80. }
  81. return $this;
  82. }
  83. $this->vars[$var_name] = $var_value;
  84. return $this;
  85. }
  86. public function addPlugin($prefix, $callback)
  87. {
  88. $this->plugins[$prefix] = $callback;
  89. }
  90. }