Skip to content

Commit b12ff68

Browse files
ianlancetaylorromaindoumenc
authored andcommitted
text/template: correct assignment, not declaration, in range
We were mishandling {{range $i = .}}, treating it as though it were {{range $i := .}}. That happened to work if $i were the most recently declared variable, but not otherwise. Fixes golang#56490 Change-Id: I222a009d671d86c06a980a54388e05f12101c00b Reviewed-on: https://go-review.googlesource.com/c/go/+/446795 Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Rob Pike <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Bryan Mills <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]>
1 parent 06a458a commit b12ff68

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/text/template/exec.go

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,11 +363,19 @@ func (s *state) walkRange(dot reflect.Value, r *parse.RangeNode) {
363363
oneIteration := func(index, elem reflect.Value) {
364364
// Set top var (lexically the second if there are two) to the element.
365365
if len(r.Pipe.Decl) > 0 {
366-
s.setTopVar(1, elem)
366+
if r.Pipe.IsAssign {
367+
s.setVar(r.Pipe.Decl[0].Ident[0], elem)
368+
} else {
369+
s.setTopVar(1, elem)
370+
}
367371
}
368372
// Set next var (lexically the first if there are two) to the index.
369373
if len(r.Pipe.Decl) > 1 {
370-
s.setTopVar(2, index)
374+
if r.Pipe.IsAssign {
375+
s.setVar(r.Pipe.Decl[1].Ident[0], index)
376+
} else {
377+
s.setTopVar(2, index)
378+
}
371379
}
372380
defer s.pop(mark)
373381
defer func() {

src/text/template/exec_test.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -692,6 +692,8 @@ var execTests = []execTest{
692692
{"bug18a", "{{eq . '.'}}", "true", '.', true},
693693
{"bug18b", "{{eq . 'e'}}", "true", 'e', true},
694694
{"bug18c", "{{eq . 'P'}}", "true", 'P', true},
695+
696+
{"issue56490", "{{$i := 0}}{{$x := 0}}{{range $i = .AI}}{{end}}{{$i}}", "5", tVal, true},
695697
}
696698

697699
func zeroArgs() string {

0 commit comments

Comments
 (0)