Use.php 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2011 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Imports blocks defined in another template into the current template.
  12. *
  13. * <pre>
  14. * {% extends "base.html" %}
  15. *
  16. * {% use "blocks.html" %}
  17. *
  18. * {% block title %}{% endblock %}
  19. * {% block content %}{% endblock %}
  20. * </pre>
  21. *
  22. * @see http://www.twig-project.org/doc/templates.html#horizontal-reuse for details.
  23. */
  24. class Twig_TokenParser_Use extends Twig_TokenParser
  25. {
  26. /**
  27. * Parses a token and returns a node.
  28. *
  29. * @param Twig_Token $token A Twig_Token instance
  30. *
  31. * @return Twig_NodeInterface A Twig_NodeInterface instance
  32. */
  33. public function parse(Twig_Token $token)
  34. {
  35. $template = $this->parser->getExpressionParser()->parseExpression();
  36. if (!$template instanceof Twig_Node_Expression_Constant) {
  37. throw new Twig_Error_Syntax('The template references in a "use" statement must be a string.', $token->getLine());
  38. }
  39. $stream = $this->parser->getStream();
  40. $targets = array();
  41. if ($stream->test('with')) {
  42. $stream->next();
  43. do {
  44. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  45. $alias = $name;
  46. if ($stream->test('as')) {
  47. $stream->next();
  48. $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  49. }
  50. $targets[$name] = new Twig_Node_Expression_Constant($alias, -1);
  51. if (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ',')) {
  52. break;
  53. }
  54. $stream->next();
  55. } while (true);
  56. }
  57. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  58. $this->parser->addTrait(new Twig_Node(array('template' => $template, 'targets' => new Twig_Node($targets))));
  59. return null;
  60. }
  61. /**
  62. * Gets the tag name associated with this token parser.
  63. *
  64. * @param string The tag name
  65. */
  66. public function getTag()
  67. {
  68. return 'use';
  69. }
  70. }