Use.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. public function parse(Twig_Token $token)
  27. {
  28. $template = $this->parser->getExpressionParser()->parseExpression();
  29. $stream = $this->parser->getStream();
  30. if (!$template instanceof Twig_Node_Expression_Constant) {
  31. throw new Twig_Error_Syntax('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getFilename());
  32. }
  33. $targets = array();
  34. if ($stream->nextIf('with')) {
  35. do {
  36. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  37. $alias = $name;
  38. if ($stream->nextIf('as')) {
  39. $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  40. }
  41. $targets[$name] = new Twig_Node_Expression_Constant($alias, -1);
  42. if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) {
  43. break;
  44. }
  45. } while (true);
  46. }
  47. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  48. $this->parser->addTrait(new Twig_Node(array('template' => $template, 'targets' => new Twig_Node($targets))));
  49. }
  50. public function getTag()
  51. {
  52. return 'use';
  53. }
  54. }