Macro.php 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. /**
  22. * Parses a token and returns a node.
  23. *
  24. * @param Twig_Token $token A Twig_Token instance
  25. *
  26. * @return Twig_NodeInterface A Twig_NodeInterface instance
  27. */
  28. public function parse(Twig_Token $token)
  29. {
  30. $lineno = $token->getLine();
  31. $name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
  32. $arguments = $this->parser->getExpressionParser()->parseArguments();
  33. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  34. $this->parser->pushLocalScope();
  35. $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  36. if ($this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
  37. $value = $this->parser->getStream()->next()->getValue();
  38. if ($value != $name) {
  39. throw new Twig_Error_Syntax(sprintf("Expected endmacro for macro '$name' (but %s given)", $value), $lineno);
  40. }
  41. }
  42. $this->parser->popLocalScope();
  43. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  44. $this->parser->setMacro($name, new Twig_Node_Macro($name, $body, $arguments, $lineno, $this->getTag()));
  45. return null;
  46. }
  47. public function decideBlockEnd(Twig_Token $token)
  48. {
  49. return $token->test('endmacro');
  50. }
  51. /**
  52. * Gets the tag name associated with this token parser.
  53. *
  54. * @param string The tag name
  55. */
  56. public function getTag()
  57. {
  58. return 'macro';
  59. }
  60. }