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.

Twig.php 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Blog\View;
  3. use Twig\Loader\FilesystemLoader;
  4. use Twig\Environment;
  5. class Twig
  6. {
  7. protected $twig;
  8. protected $variables;
  9. public function __construct($tmpl_folder)
  10. {
  11. $loader = new FilesystemLoader($tmpl_folder);
  12. $this->twig = new Environment($loader, []);
  13. $this->variables = ['navbar' => [], 'messages' => ['msgs' => []], 'footer' => []];
  14. }
  15. protected function load($tmpl)
  16. {
  17. return $this->twig->load($tmpl);
  18. }
  19. public function addMessage($msg)
  20. {
  21. $current = $this->variables['messages']['msgs'];
  22. $current[] = $msg;
  23. $this->variables['messages']['msgs'] = $current;
  24. }
  25. // add block variables to the global variable bag
  26. public function addBlockVariable($block, $data)
  27. {
  28. $current = $this->variables[$block];
  29. if ($current) {
  30. $new = array_merge($current, $data);
  31. } else {
  32. $new = $data;
  33. }
  34. $this->variables[$block] = $new;
  35. }
  36. public function render($tmpl, $vars)
  37. {
  38. $template = $this->load($tmpl);
  39. $variables = array_merge($this->variables, $vars);
  40. return $template->render($variables);
  41. }
  42. }