diff --git a/mode/soy/soy.js b/mode/soy/soy.js
index 9fd75c6d27f25ac1beff53a4f92978211c3eeebb..3876333f94f7c8072eac34b210717f31da7936ff 100644
--- a/mode/soy/soy.js
+++ b/mode/soy/soy.js
@@ -60,16 +60,19 @@
       };
     }
 
-    function pop(list) {
-      return list && list.next;
-    }
-
     // Reference a variable `name` in `list`.
     // Let `loose` be truthy to ignore missing identifiers.
     function ref(list, name, loose) {
       return contains(list, name) ? "variable-2" : (loose ? "variable" : "variable-2 error");
     }
 
+    function popscope(state) {
+      if (state.scopes) {
+        state.variables = state.scopes.element;
+        state.scopes = state.scopes.next;
+      }
+    }
+
     return {
       startState: function() {
         return {
@@ -168,11 +171,11 @@
           case "tag":
             if (stream.match(/^\/?}/)) {
               if (state.tag == "/template" || state.tag == "/deltemplate") {
-                state.variables = state.scopes = pop(state.scopes);
+                popscope(state);
                 state.indent = 0;
               } else {
                 if (state.tag == "/for" || state.tag == "/foreach") {
-                  state.variables = state.scopes = pop(state.scopes);
+                  popscope(state);
                 }
                 state.indent -= config.indentUnit *
                     (stream.current() == "/}" || indentingTags.indexOf(state.tag) == -1 ? 2 : 1);
diff --git a/mode/soy/test.js b/mode/soy/test.js
index 1a962de3e7987601acb96ffc916ec5a605b67d45..1a4c6c934fc63abe90ba912fb3b5bbf2e28aae37 100644
--- a/mode/soy/test.js
+++ b/mode/soy/test.js
@@ -60,10 +60,12 @@
      '');
 
   MT('foreach-scope-test',
+     '[keyword {@param] [def bar]: [variable-3 string][keyword }]',
      '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]',
      '  [keyword {][variable-2 $foo][keyword }]',
      '[keyword {/foreach}]',
-     '[keyword {][variable-2&error $foo][keyword }]');
+     '[keyword {][variable-2&error $foo][keyword }]',
+     '[keyword {][variable-2 $bar][keyword }]');
 
   MT('foreach-ifempty-indent-test',
      '[keyword {foreach] [def $foo] [keyword in] [variable-2&error $foos][keyword }]',