Twig.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. <?php
  2. namespace Grav\Common\Twig;
  3. use Grav\Common\Grav;
  4. use Grav\Common\Config\Config;
  5. use Grav\Common\Page\Page;
  6. use Grav\Common\Inflector;
  7. use Grav\Common\Utils;
  8. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  9. use RocketTheme\Toolbox\Event\Event;
  10. /**
  11. * The Twig object handles all the Twig template rendering for Grav. It's a singleton object
  12. * that is optimized so that it only needs to be initialized once and can be reused for individual
  13. * page template rendering as well as the main site template rendering.
  14. *
  15. * @author RocketTheme
  16. * @license MIT
  17. */
  18. class Twig
  19. {
  20. /**
  21. * @var \Twig_Environment
  22. */
  23. public $twig;
  24. /**
  25. * @var array
  26. */
  27. public $twig_vars;
  28. /**
  29. * @var array
  30. */
  31. public $twig_paths;
  32. /**
  33. * @var string
  34. */
  35. public $template;
  36. /**
  37. * @var Grav
  38. */
  39. protected $grav;
  40. /**
  41. * @var \Twig_Loader_Filesystem
  42. */
  43. protected $loader;
  44. /**
  45. * @var \Twig_Loader_Array
  46. */
  47. protected $loaderArray;
  48. /**
  49. * Constructor
  50. */
  51. public function __construct(Grav $grav)
  52. {
  53. $this->grav = $grav;
  54. $this->twig_paths = [];
  55. }
  56. /**
  57. * Twig initialization that sets the twig loader chain, then the environment, then extensions
  58. * and also the base set of twig vars
  59. */
  60. public function init()
  61. {
  62. if (!isset($this->twig)) {
  63. /** @var Config $config */
  64. $config = $this->grav['config'];
  65. /** @var UniformResourceLocator $locator */
  66. $locator = $this->grav['locator'];
  67. $debugger = $this->grav['debugger'];
  68. /** @var Language $language */
  69. $language = $this->grav['language'];
  70. $active_language = $language->getActive();
  71. $language_append = $active_language ? '/'.$active_language : '';
  72. // handle language templates if available
  73. if ($language->enabled()) {
  74. $lang_templates = $locator->findResource('theme://templates/'.($active_language ? $active_language : $language->getDefault()));
  75. if ($lang_templates) {
  76. $this->twig_paths[] = $lang_templates;
  77. }
  78. }
  79. $this->twig_paths = array_merge($this->twig_paths, $locator->findResources('theme://templates'));
  80. $this->grav->fireEvent('onTwigTemplatePaths');
  81. $this->loader = new \Twig_Loader_Filesystem($this->twig_paths);
  82. $this->loaderArray = new \Twig_Loader_Array(array());
  83. $loader_chain = new \Twig_Loader_Chain(array($this->loaderArray, $this->loader));
  84. $params = $config->get('system.twig');
  85. if (!empty($params['cache'])) {
  86. $params['cache'] = $locator->findResource('cache://twig', true, true);
  87. }
  88. $this->twig = new TwigEnvironment($loader_chain, $params);
  89. if ($config->get('system.twig.undefined_functions')) {
  90. $this->twig->registerUndefinedFunctionCallback(function ($name) {
  91. if (function_exists($name)) {
  92. return new \Twig_Function_Function($name);
  93. }
  94. return new \Twig_Function_Function(function() {});
  95. });
  96. }
  97. if ($config->get('system.twig.undefined_filters')) {
  98. $this->twig->registerUndefinedFilterCallback(function ($name) {
  99. if (function_exists($name)) {
  100. return new \Twig_Filter_Function($name);
  101. }
  102. return new \Twig_Filter_Function(function() {});
  103. });
  104. }
  105. $this->grav->fireEvent('onTwigInitialized');
  106. // set default date format if set in config
  107. if ($config->get('system.pages.dateformat.long')) {
  108. $this->twig->getExtension('core')->setDateFormat($config->get('system.pages.dateformat.long'));
  109. }
  110. // enable the debug extension if required
  111. if ($config->get('system.twig.debug')) {
  112. $this->twig->addExtension(new \Twig_Extension_Debug());
  113. }
  114. $this->twig->addExtension(new TwigExtension());
  115. $this->grav->fireEvent('onTwigExtensions');
  116. // Set some standard variables for twig
  117. $this->twig_vars = array(
  118. 'config' => $config,
  119. 'uri' => $this->grav['uri'],
  120. 'base_dir' => rtrim(ROOT_DIR, '/'),
  121. 'base_url' => $this->grav['base_url'] . $language_append,
  122. 'base_url_simple' => $this->grav['base_url'],
  123. 'base_url_absolute' => $this->grav['base_url_absolute'] . $language_append,
  124. 'base_url_relative' => $this->grav['base_url_relative'] . $language_append,
  125. 'theme_dir' => $locator->findResource('theme://'),
  126. 'theme_url' => $this->grav['base_url'] .'/'. $locator->findResource('theme://', false),
  127. 'site' => $config->get('site'),
  128. 'assets' => $this->grav['assets'],
  129. 'taxonomy' => $this->grav['taxonomy'],
  130. 'browser' => $this->grav['browser'],
  131. );
  132. }
  133. }
  134. /**
  135. * @return \Twig_Environment
  136. */
  137. public function twig()
  138. {
  139. return $this->twig;
  140. }
  141. /**
  142. * @return \Twig_Loader_Filesystem
  143. */
  144. public function loader()
  145. {
  146. return $this->loader;
  147. }
  148. /**
  149. * Adds or overrides a template.
  150. *
  151. * @param string $name The template name
  152. * @param string $template The template source
  153. */
  154. public function setTemplate($name, $template)
  155. {
  156. $this->loaderArray->setTemplate($name, $template);
  157. }
  158. /**
  159. * Twig process that renders a page item. It supports two variations:
  160. * 1) Handles modular pages by rendering a specific page based on its modular twig template
  161. * 2) Renders individual page items for twig processing before the site rendering
  162. *
  163. * @param Page $item The page item to render
  164. * @param string $content Optional content override
  165. * @return string The rendered output
  166. * @throws \Twig_Error_Loader
  167. */
  168. public function processPage(Page $item, $content = null)
  169. {
  170. $content = $content !== null ? $content : $item->content();
  171. // override the twig header vars for local resolution
  172. $this->grav->fireEvent('onTwigPageVariables', new Event(['page' => $item]));
  173. $twig_vars = $this->twig_vars;
  174. $twig_vars['page'] = $item;
  175. $twig_vars['media'] = $item->media();
  176. $twig_vars['header'] = $item->header();
  177. $local_twig = clone($this->twig);
  178. $modular_twig = $item->modularTwig();
  179. $process_twig = isset($item->header()->process['twig']) ? $item->header()->process['twig'] : false;
  180. try {
  181. // Process Modular Twig
  182. if ($modular_twig) {
  183. $twig_vars['content'] = $content;
  184. $template = $item->template() . TEMPLATE_EXT;
  185. $output = $content = $local_twig->render($template, $twig_vars);
  186. }
  187. // Process in-page Twig
  188. if (!$modular_twig || ($modular_twig && $process_twig)) {
  189. $name = '@Page:' . $item->path();
  190. $this->setTemplate($name, $content);
  191. $output = $local_twig->render($name, $twig_vars);
  192. }
  193. } catch (\Twig_Error_Loader $e) {
  194. throw new \RuntimeException($e->getRawMessage(), 404, $e);
  195. }
  196. return $output;
  197. }
  198. /**
  199. * Process a Twig template directly by using a template name
  200. * and optional array of variables
  201. *
  202. * @param string $template template to render with
  203. * @param array $vars Optional variables
  204. * @return string
  205. */
  206. public function processTemplate($template, $vars = array())
  207. {
  208. // override the twig header vars for local resolution
  209. $this->grav->fireEvent('onTwigTemplateVariables');
  210. $vars += $this->twig_vars;
  211. try {
  212. $output = $this->twig->render($template, $vars);
  213. } catch (\Twig_Error_Loader $e) {
  214. throw new \RuntimeException($e->getRawMessage(), 404, $e);
  215. }
  216. return $output;
  217. }
  218. /**
  219. * Process a Twig template directly by using a Twig string
  220. * and optional array of variables
  221. *
  222. * @param string $string string to render.
  223. * @param array $vars Optional variables
  224. * @return string
  225. */
  226. public function processString($string, array $vars = array())
  227. {
  228. // override the twig header vars for local resolution
  229. $this->grav->fireEvent('onTwigStringVariables');
  230. $vars += $this->twig_vars;
  231. $name = '@Var:' . $string;
  232. $this->setTemplate($name, $string);
  233. try {
  234. $output = $this->twig->render($name, $vars);
  235. } catch (\Twig_Error_Loader $e) {
  236. throw new \RuntimeException($e->getRawMessage(), 404, $e);
  237. }
  238. return $output;
  239. }
  240. /**
  241. * Twig process that renders the site layout. This is the main twig process that renders the overall
  242. * page and handles all the layout for the site display.
  243. *
  244. * @param string $format Output format (defaults to HTML).
  245. * @return string the rendered output
  246. * @throws \RuntimeException
  247. */
  248. public function processSite($format = null)
  249. {
  250. // set the page now its been processed
  251. $this->grav->fireEvent('onTwigSiteVariables');
  252. $pages = $this->grav['pages'];
  253. $page = $this->grav['page'];
  254. $content = $page->content();
  255. $config = $this->grav['config'];
  256. $twig_vars = $this->twig_vars;
  257. $twig_vars['pages'] = $pages->root();
  258. $twig_vars['page'] = $page;
  259. $twig_vars['header'] = $page->header();
  260. $twig_vars['media'] = $page->media();
  261. $twig_vars['content'] = $content;
  262. $ext = '.' . ($format ? $format : 'html') . TWIG_EXT;
  263. // determine if params are set, if so disable twig cache
  264. $params = $this->grav['uri']->params(null, true);
  265. if (!empty($params)) {
  266. $this->twig->setCache(false);
  267. }
  268. // Get Twig template layout
  269. $template = $this->template($page->template() . $ext);
  270. try {
  271. $output = $this->twig->render($template, $twig_vars);
  272. } catch (\Twig_Error_Loader $e) {
  273. $error_msg = $e->getMessage();
  274. // Try html version of this template if initial template was NOT html
  275. if ($ext != '.html'.TWIG_EXT) {
  276. try {
  277. $output = $this->twig->render($page->template().'.html'.TWIG_EXT, $twig_vars);
  278. } catch (\Twig_Error_Loader $e) {
  279. throw new \RuntimeException($error_msg, 400, $e);
  280. }
  281. } else {
  282. throw new \RuntimeException($error_msg, 400, $e);
  283. }
  284. }
  285. return $output;
  286. }
  287. /**
  288. * Simple helper method to get the twig template if it has already been set, else return
  289. * the one being passed in
  290. *
  291. * @param string $template the template name
  292. * @return string the template name
  293. */
  294. public function template($template)
  295. {
  296. if (isset($this->template)) {
  297. return $this->template;
  298. } else {
  299. return $template;
  300. }
  301. }
  302. }