Include.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Twig_Node_Include extends Twig_Node implements Twig_NodeOutputInterface
  17. {
  18. public function __construct(Twig_Node_Expression $expr, Twig_Node_Expression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null)
  19. {
  20. parent::__construct(array('expr' => $expr, 'variables' => $variables), array('only' => (bool) $only, 'ignore_missing' => (bool) $ignoreMissing), $lineno, $tag);
  21. }
  22. public function compile(Twig_Compiler $compiler)
  23. {
  24. $compiler->addDebugInfo($this);
  25. if ($this->getAttribute('ignore_missing')) {
  26. $compiler
  27. ->write("try {\n")
  28. ->indent()
  29. ;
  30. }
  31. $this->addGetTemplate($compiler);
  32. $compiler->raw('->display(');
  33. $this->addTemplateArguments($compiler);
  34. $compiler->raw(");\n");
  35. if ($this->getAttribute('ignore_missing')) {
  36. $compiler
  37. ->outdent()
  38. ->write("} catch (Twig_Error_Loader \$e) {\n")
  39. ->indent()
  40. ->write("// ignore missing template\n")
  41. ->outdent()
  42. ->write("}\n\n")
  43. ;
  44. }
  45. }
  46. protected function addGetTemplate(Twig_Compiler $compiler)
  47. {
  48. $compiler
  49. ->write('$this->loadTemplate(')
  50. ->subcompile($this->getNode('expr'))
  51. ->raw(', ')
  52. ->repr($compiler->getFilename())
  53. ->raw(', ')
  54. ->repr($this->getLine())
  55. ->raw(')')
  56. ;
  57. }
  58. protected function addTemplateArguments(Twig_Compiler $compiler)
  59. {
  60. if (null === $this->getNode('variables')) {
  61. $compiler->raw(false === $this->getAttribute('only') ? '$context' : 'array()');
  62. } elseif (false === $this->getAttribute('only')) {
  63. $compiler
  64. ->raw('array_merge($context, ')
  65. ->subcompile($this->getNode('variables'))
  66. ->raw(')')
  67. ;
  68. } else {
  69. $compiler->subcompile($this->getNode('variables'));
  70. }
  71. }
  72. }