Macro.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 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. * Defines a macro.
  12. *
  13. * <pre>
  14. * {% macro input(name, value, type, size) %}
  15. * <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
  16. * {% endmacro %}
  17. * </pre>
  18. */
  19. class Twig_TokenParser_Macro extends Twig_TokenParser
  20. {
  21. public function parse(Twig_Token $token)
  22. {
  23. $lineno = $token->getLine();
  24. $stream = $this->parser->getStream();
  25. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  26. $arguments = $this->parser->getExpressionParser()->parseArguments(true, true);
  27. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  28. $this->parser->pushLocalScope();
  29. $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  30. if ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) {
  31. $value = $token->getValue();
  32. if ($value != $name) {
  33. throw new Twig_Error_Syntax(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getFilename());
  34. }
  35. }
  36. $this->parser->popLocalScope();
  37. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  38. $this->parser->setMacro($name, new Twig_Node_Macro($name, new Twig_Node_Body(array($body)), $arguments, $lineno, $this->getTag()));
  39. }
  40. public function decideBlockEnd(Twig_Token $token)
  41. {
  42. return $token->test('endmacro');
  43. }
  44. public function getTag()
  45. {
  46. return 'macro';
  47. }
  48. }