TwigWrapper.class.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. class TwigWrapper
  3. {
  4. private $htmlPath;
  5. public function __construct($htmlPath)
  6. {
  7. $this->setHtmlPath($htmlPath);
  8. $this->initTwig();
  9. }
  10. private function initTwig()
  11. {
  12. Twig_Autoloader::register();
  13. $loader = new Twig_Loader_Filesystem($this->htmlPath);
  14. $this->twig = new Twig_Environment($loader, array());
  15. }
  16. public function setHtmlPath($htmlPath)
  17. {
  18. if(!file_exists($htmlPath))
  19. {
  20. throw new TwigClassException('Path does not exist');
  21. }
  22. $this->htmlPath = $htmlPath;
  23. }
  24. public function render($file, $options)
  25. {
  26. $options['all'] = array_keys($options);
  27. return $this->twig->render($file, $options);
  28. }
  29. public function createSimpleFunc($name, /*callable*/ $function)
  30. {
  31. if(!is_callable($function))
  32. {
  33. throw new TwigClassException('Second param must be a function');
  34. }
  35. return $this->twig->addFunction(new Twig_SimpleFunction($name, $function));
  36. }
  37. public function createSimpleFilter($name, /*callable*/ $function)
  38. {
  39. if(!is_callable($function))
  40. {
  41. throw new TwigClassException('Second param must be a function');
  42. }
  43. return $this->twig->addFilter(new Twig_SimpleFilter($name, $function));
  44. }
  45. }
  46. class TwigClassException extends Exception
  47. {
  48. }