Include.php 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. * (c) 2009 Armin Ronacher
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. /**
  12. * Represents an include node.
  13. *
  14. * @package twig
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class Twig_Node_Include extends Twig_Node implements Twig_NodeOutputInterface
  18. {
  19. public function __construct(Twig_Node_Expression $expr, Twig_Node_Expression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null)
  20. {
  21. parent::__construct(array('expr' => $expr, 'variables' => $variables), array('only' => (Boolean) $only, 'ignore_missing' => (Boolean) $ignoreMissing), $lineno, $tag);
  22. }
  23. /**
  24. * Compiles the node to PHP.
  25. *
  26. * @param Twig_Compiler A Twig_Compiler instance
  27. */
  28. public function compile(Twig_Compiler $compiler)
  29. {
  30. $compiler->addDebugInfo($this);
  31. if ($this->getAttribute('ignore_missing')) {
  32. $compiler
  33. ->write("try {\n")
  34. ->indent()
  35. ;
  36. }
  37. if ($this->getNode('expr') instanceof Twig_Node_Expression_Constant) {
  38. $compiler
  39. ->write("\$this->env->loadTemplate(")
  40. ->subcompile($this->getNode('expr'))
  41. ->raw(")->display(")
  42. ;
  43. } else {
  44. $compiler
  45. ->write("\$template = \$this->env->resolveTemplate(")
  46. ->subcompile($this->getNode('expr'))
  47. ->raw(");\n")
  48. ->write('$template->display(')
  49. ;
  50. }
  51. if (false === $this->getAttribute('only')) {
  52. if (null === $this->getNode('variables')) {
  53. $compiler->raw('$context');
  54. } else {
  55. $compiler
  56. ->raw('array_merge($context, ')
  57. ->subcompile($this->getNode('variables'))
  58. ->raw(')')
  59. ;
  60. }
  61. } else {
  62. if (null === $this->getNode('variables')) {
  63. $compiler->raw('array()');
  64. } else {
  65. $compiler->subcompile($this->getNode('variables'));
  66. }
  67. }
  68. $compiler->raw(");\n");
  69. if ($this->getAttribute('ignore_missing')) {
  70. $compiler
  71. ->outdent()
  72. ->write("} catch (Twig_Error_Loader \$e) {\n")
  73. ->indent()
  74. ->write("// ignore missing template\n")
  75. ->outdent()
  76. ->write("}\n\n")
  77. ;
  78. }
  79. }
  80. }