Permalink
Browse files

fixed variables defined outside a loop and for which the value change…

…s in a for loop (closes #43)
  • Loading branch information...
fabpot committed May 11, 2010
1 parent 29edbed commit 2e1b12bcce0f6a31259f84271352e63cb49e4e03
Showing with 28 additions and 27 deletions.
  1. +1 −0 CHANGELOG
  2. +0 −25 lib/Twig/Compiler.php
  3. +10 −2 lib/Twig/Node/For.php
  4. +17 −0 test/fixtures/tags/for/inner_variables.test
View
@@ -1,5 +1,6 @@
* 0.9.6-DEV
+ * fixed variables defined outside a loop and for which the value changes in a for loop
* fixed the test suite for PHP 5.2 and older versions of PHPUnit
* added support for __call() in expression resolution
* fixed node visiting for macros (macros are now visited by visitors as any other node)
View
@@ -151,31 +151,6 @@ public function repr($value)
return $this;
}
- /**
- * Pushes the current context on the stack.
- *
- * @return Twig_Compiler The current compiler instance
- */
- public function pushContext()
- {
- // the (array) cast bypasses a PHP 5.2.6 bug
- $this->write('$context[\'_parent\'] = (array) $context;'."\n");
-
- return $this;
- }
-
- /**
- * Pops a context from the stack.
- *
- * @return Twig_Compiler The current compiler instance
- */
- public function popContext()
- {
- $this->write('$context = $context[\'_parent\'];'."\n");
-
- return $this;
- }
-
/**
* Adds debugging information.
*
View
@@ -52,7 +52,8 @@ public function compile($compiler)
{
$compiler
->addDebugInfo($this)
- ->pushContext()
+ // the (array) cast bypasses a PHP 5.2.6 bug
+ ->write('$context[\'_parent\'] = (array) $context;'."\n")
;
if (!is_null($this->else)) {
@@ -130,7 +131,14 @@ public function compile($compiler)
->write("}\n")
;
}
- $compiler->popContext();
+
+ $compiler->write('$_parent = $context[\'_parent\'];'."\n");
+
+ // remove some "private" loop variables (needed for nested loops)
+ $compiler->write('unset($context[\'_seq\'], $context[\'_iterated\'], $context[\''.$loopVars[0].'\'], $context[\''.$loopVars[1].'\'], $context[\'_parent\'], $context[\'loop\']);'."\n");
+
+ /// keep the values set in the inner context for variables defined in the outer context
+ $compiler->write('$context = array_merge($_parent, array_intersect_key($context, $_parent));'."\n");
}
public function setWithLoop($boolean)
@@ -0,0 +1,17 @@
+--TEST--
+"for" tag does not reset inner variables
+--TEMPLATE--
+{% for i in 1..2 %}
+ {% for j in 0..2 %}
+ {{k}}{% set k as k+1 %} {{ loop.parent.loop.index }}
+ {% endfor %}
+{% endfor %}
+--DATA--
+return array('k' => 0)
+--EXPECT--
+ 0 1
+ 1 1
+ 2 1
+ 3 2
+ 4 2
+ 5 2

0 comments on commit 2e1b12b

Please sign in to comment.