SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/TwigView.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2017 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use Kohana_Exception;
  17. use Twig\Environment;
  18. use Twig\Loader\ArrayLoader;
  19. use Twig\Extension\DebugExtension;
  20.  
  21. /**
  22.  * Renderer for twig engine
  23.  *
  24.  * @todo - There's lots of opportunity to cache these templates.
  25.  */
  26. class TwigView extends View
  27. {
  28. protected static $EXTENSION = '.twig';
  29.  
  30. /** @var Environment */
  31. protected static $twig;
  32.  
  33. /** @var TwigSkinLoader */
  34. protected static $loader;
  35.  
  36. /** @var string */
  37. protected $kohana_template_name;
  38.  
  39.  
  40. /** @inheritdoc */
  41. public function __construct($name, array $data = [])
  42. {
  43. // Initialise the twig renderer.
  44. if (!isset(self::$twig)) {
  45. self::$loader = new TwigSkinLoader();
  46. self::$twig = new Environment(self::$loader, [
  47. 'debug' => !IN_PRODUCTION,
  48. 'strict_variables' => !IN_PRODUCTION,
  49. ]);
  50.  
  51. if (!IN_PRODUCTION) {
  52. self::$twig->addExtension(new DebugExtension());
  53. }
  54.  
  55. self::$twig->addExtension(new SproutExtension());
  56. }
  57.  
  58. $this->kohana_template_name = $name;
  59. parent::__construct($name, $data);
  60. }
  61.  
  62.  
  63. /** @inheritdoc */
  64. public function render($print = FALSE, $renderer = FALSE)
  65. {
  66. if (empty($this->kohana_filename)) {
  67. throw new Kohana_Exception('core.view_set_filename');
  68. }
  69.  
  70. $output = self::$twig->render($this->kohana_template_name, $this->kohana_local_data);
  71.  
  72. if ($renderer !== FALSE AND is_callable($renderer, TRUE))
  73. {
  74. // Pass the output through the user defined renderer
  75. $output = call_user_func($renderer, $output);
  76. }
  77.  
  78. if ($print === TRUE)
  79. {
  80. // Display the output
  81. echo $output;
  82. return;
  83. }
  84.  
  85. return $output;
  86. }
  87. }
  88.