Include.php 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. $this->addGetTemplate($compiler);
  38. $compiler->raw('->display(');
  39. $this->addTemplateArguments($compiler);
  40. $compiler->raw(");\n");
  41. if ($this->getAttribute('ignore_missing')) {
  42. $compiler
  43. ->outdent()
  44. ->write("} catch (Twig_Error_Loader \$e) {\n")
  45. ->indent()
  46. ->write("// ignore missing template\n")
  47. ->outdent()
  48. ->write("}\n\n")
  49. ;
  50. }
  51. }
  52. protected function addGetTemplate(Twig_Compiler $compiler)
  53. {
  54. if ($this->getNode('expr') instanceof Twig_Node_Expression_Constant) {
  55. $compiler
  56. ->write("\$this->env->loadTemplate(")
  57. ->subcompile($this->getNode('expr'))
  58. ->raw(")")
  59. ;
  60. } else {
  61. $compiler
  62. ->write("\$template = \$this->env->resolveTemplate(")
  63. ->subcompile($this->getNode('expr'))
  64. ->raw(");\n")
  65. ->write('$template')
  66. ;
  67. }
  68. }
  69. protected function addTemplateArguments(Twig_Compiler $compiler)
  70. {
  71. if (false === $this->getAttribute('only')) {
  72. if (null === $this->getNode('variables')) {
  73. $compiler->raw('$context');
  74. } else {
  75. $compiler
  76. ->raw('array_merge($context, ')
  77. ->subcompile($this->getNode('variables'))
  78. ->raw(')')
  79. ;
  80. }
  81. } else {
  82. if (null === $this->getNode('variables')) {
  83. $compiler->raw('array()');
  84. } else {
  85. $compiler->subcompile($this->getNode('variables'));
  86. }
  87. }
  88. }
  89. }