Block.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * Marks a section of a template as being reusable.
  13. *
  14. * <pre>
  15. * {% block head %}
  16. * <link rel="stylesheet" href="style.css" />
  17. * <title>{% block title %}{% endblock %} - My Webpage</title>
  18. * {% endblock %}
  19. * </pre>
  20. */
  21. class Twig_TokenParser_Block extends Twig_TokenParser
  22. {
  23. public function parse(Twig_Token $token)
  24. {
  25. $lineno = $token->getLine();
  26. $stream = $this->parser->getStream();
  27. $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue();
  28. if ($this->parser->hasBlock($name)) {
  29. throw new Twig_Error_Syntax(sprintf("The block '%s' has already been defined line %d.", $name, $this->parser->getBlock($name)->getLine()), $stream->getCurrent()->getLine(), $stream->getFilename());
  30. }
  31. $this->parser->setBlock($name, $block = new Twig_Node_Block($name, new Twig_Node(array()), $lineno));
  32. $this->parser->pushLocalScope();
  33. $this->parser->pushBlockStack($name);
  34. if ($stream->nextIf(Twig_Token::BLOCK_END_TYPE)) {
  35. $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  36. if ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) {
  37. $value = $token->getValue();
  38. if ($value != $name) {
  39. throw new Twig_Error_Syntax(sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getFilename());
  40. }
  41. }
  42. } else {
  43. $body = new Twig_Node(array(
  44. new Twig_Node_Print($this->parser->getExpressionParser()->parseExpression(), $lineno),
  45. ));
  46. }
  47. $stream->expect(Twig_Token::BLOCK_END_TYPE);
  48. $block->setNode('body', $body);
  49. $this->parser->popBlockStack();
  50. $this->parser->popLocalScope();
  51. return new Twig_Node_BlockReference($name, $lineno, $this->getTag());
  52. }
  53. public function decideBlockEnd(Twig_Token $token)
  54. {
  55. return $token->test('endblock');
  56. }
  57. public function getTag()
  58. {
  59. return 'block';
  60. }
  61. }