For.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. * Loops over each item of a sequence.
  13. *
  14. * <pre>
  15. * <ul>
  16. * {% for user in users %}
  17. * <li>{{ user.username|e }}</li>
  18. * {% endfor %}
  19. * </ul>
  20. * </pre>
  21. */
  22. class Twig_TokenParser_For extends Twig_TokenParser
  23. {
  24. /**
  25. * Parses a token and returns a node.
  26. *
  27. * @param Twig_Token $token A Twig_Token instance
  28. *
  29. * @return Twig_NodeInterface A Twig_NodeInterface instance
  30. */
  31. public function parse(Twig_Token $token)
  32. {
  33. $lineno = $token->getLine();
  34. $targets = $this->parser->getExpressionParser()->parseAssignmentExpression();
  35. $this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, 'in');
  36. $seq = $this->parser->getExpressionParser()->parseExpression();
  37. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  38. $body = $this->parser->subparse(array($this, 'decideForFork'));
  39. if ($this->parser->getStream()->next()->getValue() == 'else') {
  40. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  41. $else = $this->parser->subparse(array($this, 'decideForEnd'), true);
  42. } else {
  43. $else = null;
  44. }
  45. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  46. if (count($targets) > 1) {
  47. $keyTarget = $targets->getNode(0);
  48. $valueTarget = $targets->getNode(1);
  49. } else {
  50. $keyTarget = new Twig_Node_Expression_AssignName('_key', $lineno);
  51. $valueTarget = $targets->getNode(0);
  52. }
  53. return new Twig_Node_For($keyTarget, $valueTarget, $seq, $body, $else, $lineno, $this->getTag());
  54. }
  55. public function decideForFork(Twig_Token $token)
  56. {
  57. return $token->test(array('else', 'endfor'));
  58. }
  59. public function decideForEnd(Twig_Token $token)
  60. {
  61. return $token->test('endfor');
  62. }
  63. /**
  64. * Gets the tag name associated with this token parser.
  65. *
  66. * @param string The tag name
  67. */
  68. public function getTag()
  69. {
  70. return 'for';
  71. }
  72. }