You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

111 lines
2.9 KiB

  1. <?php
  2. /**
  3. * Простейший шаблонизатор.
  4. * Зато быстрый.
  5. *
  6. * @copyright
  7. * @link
  8. * @package Majestic
  9. * @subpackage Decorator
  10. * @since
  11. * @version SVN: $Id$
  12. * @filesource $URL$
  13. */
  14. final class Sublimer
  15. {
  16. const GLOBAL_KEY = 0;
  17. public $vars = array();
  18. public $path = '';
  19. public $template = '';
  20. protected $head_array = array();
  21. /**
  22. * Конструктор
  23. *
  24. * @param string $path - путь до шаблонов
  25. */
  26. public function __construct($path = '')
  27. {
  28. $this->setPath($path);
  29. $this->vars[self::GLOBAL_KEY] = array();
  30. }
  31. /**
  32. * Присвоить переменную только
  33. *
  34. * @param string $name - имя переменной
  35. * @param mixed $value - значение переменной
  36. * @param string $template - шаблон, если не указан, то переменная глобальная
  37. */
  38. public function assign($name, $value, $template = self::GLOBAL_KEY)
  39. {
  40. $this->vars[$template][$name] = $value;
  41. }
  42. /**
  43. * Очистить стек переменных
  44. * @param boolean $with_local - включая локальные переменные
  45. */
  46. public function clear($template = self::GLOBAL_KEY)
  47. {
  48. $this->vars[$template] = array();
  49. }
  50. /**
  51. * Обработать шаблон
  52. *
  53. * @param string $template - относительный путь до шаблона
  54. * @return string - обработанное содержимое шаблона
  55. */
  56. public function fetch($template)
  57. {
  58. $this->template = $template; //дабы экстракт не перезатер нам переменную. Это важно! $this то он не перезатрет :)
  59. extract($this->vars[self::GLOBAL_KEY]);
  60. if (isset($this->vars[$this->template])) {
  61. extract($this->vars[$this->template], EXTR_OVERWRITE);
  62. }
  63. ob_start();
  64. if (!(include $this->path.'/'.$this->template) == 'OK') {
  65. throw new MJException('Template '.$this->path.'/'.$this->template.' not found');
  66. }
  67. return ob_get_clean();
  68. }
  69. /**
  70. * Установать путь до шаблонов
  71. *
  72. * @param string $path - путь до шаблонов
  73. */
  74. public function setPath($path)
  75. {
  76. $this->path = $path;
  77. }
  78. //Функции для вызова из шаблонов.
  79. protected function addHead($str)
  80. {
  81. $this->head_array[] = $str;
  82. }
  83. protected function getHead()
  84. {
  85. return $this->head_array;
  86. }
  87. /**
  88. * обрезает текст до заданной длинны
  89. *
  90. * @param string $text
  91. * @param int $count
  92. * @param string $postfix
  93. */
  94. protected function trimString($text, $count = 15, $postfix = "...")
  95. {
  96. return mb_substr($text, 0, $count).$postfix;
  97. }
  98. }
  99. ?>