|
0
|
1 |
<?php |
|
|
2 |
|
|
|
3 |
/* |
|
|
4 |
* This file is part of Twig. |
|
|
5 |
* |
|
|
6 |
* (c) 2009 Fabien Potencier |
|
|
7 |
* (c) 2009 Armin Ronacher |
|
|
8 |
* |
|
|
9 |
* For the full copyright and license information, please view the LICENSE |
|
|
10 |
* file that was distributed with this source code. |
|
|
11 |
*/ |
|
|
12 |
|
|
|
13 |
/** |
|
|
14 |
* Loops over each item of a sequence. |
|
|
15 |
* |
|
|
16 |
* <pre> |
|
|
17 |
* <ul> |
|
|
18 |
* {% for user in users %} |
|
|
19 |
* <li>{{ user.username|e }}</li> |
|
|
20 |
* {% endfor %} |
|
|
21 |
* </ul> |
|
|
22 |
* </pre> |
|
|
23 |
*/ |
|
|
24 |
class Twig_TokenParser_For extends Twig_TokenParser |
|
|
25 |
{ |
|
|
26 |
/** |
|
|
27 |
* Parses a token and returns a node. |
|
|
28 |
* |
|
|
29 |
* @param Twig_Token $token A Twig_Token instance |
|
|
30 |
* |
|
|
31 |
* @return Twig_NodeInterface A Twig_NodeInterface instance |
|
|
32 |
*/ |
|
|
33 |
public function parse(Twig_Token $token) |
|
|
34 |
{ |
|
|
35 |
$lineno = $token->getLine(); |
|
|
36 |
$targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); |
|
|
37 |
$this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, 'in'); |
|
|
38 |
$seq = $this->parser->getExpressionParser()->parseExpression(); |
|
|
39 |
|
|
|
40 |
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
|
|
41 |
$body = $this->parser->subparse(array($this, 'decideForFork')); |
|
|
42 |
if ($this->parser->getStream()->next()->getValue() == 'else') { |
|
|
43 |
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
|
|
44 |
$else = $this->parser->subparse(array($this, 'decideForEnd'), true); |
|
|
45 |
} else { |
|
|
46 |
$else = null; |
|
|
47 |
} |
|
|
48 |
$this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); |
|
|
49 |
|
|
|
50 |
if (count($targets) > 1) { |
|
|
51 |
$keyTarget = $targets->getNode(0); |
|
|
52 |
$valueTarget = $targets->getNode(1); |
|
|
53 |
} else { |
|
|
54 |
$keyTarget = new Twig_Node_Expression_AssignName('_key', $lineno); |
|
|
55 |
$valueTarget = $targets->getNode(0); |
|
|
56 |
} |
|
|
57 |
|
|
|
58 |
return new Twig_Node_For($keyTarget, $valueTarget, $seq, $body, $else, $lineno, $this->getTag()); |
|
|
59 |
} |
|
|
60 |
|
|
|
61 |
public function decideForFork(Twig_Token $token) |
|
|
62 |
{ |
|
|
63 |
return $token->test(array('else', 'endfor')); |
|
|
64 |
} |
|
|
65 |
|
|
|
66 |
public function decideForEnd(Twig_Token $token) |
|
|
67 |
{ |
|
|
68 |
return $token->test('endfor'); |
|
|
69 |
} |
|
|
70 |
|
|
|
71 |
/** |
|
|
72 |
* Gets the tag name associated with this token parser. |
|
|
73 |
* |
|
|
74 |
* @param string The tag name |
|
|
75 |
*/ |
|
|
76 |
public function getTag() |
|
|
77 |
{ |
|
|
78 |
return 'for'; |
|
|
79 |
} |
|
|
80 |
} |