Skip to content

Commit 45d74aa

Browse files
beprobpike
authored andcommitted
text/template: fix truth handling of typed interface nils in if and with
Before this commit, the two logically equivalent conditionals below would produce different output: {{ if not .NonEmptyInterfaceTypedNil }}OK{{ else }}{{ end }} {{ if .NonEmptyInterfaceTypedNil }}{{ else }}OK{{ end }} The functions `not`, `or`, and `and` all use the same `truth` function, which unwraps any concrete interface value before passing it to `isTrue`. `if` and `with` also use `isTrue` to establish truth, but was missing the interface indirect call. Fixes #30501 Change-Id: I9c49eed41e737d8f162e39bef1c3b82fd5518fed GitHub-Last-Rev: 95fc2c8 GitHub-Pull-Request: #30534 Reviewed-on: https://go-review.googlesource.com/c/go/+/164958 Reviewed-by: Russ Cox <[email protected]> Run-TryBot: Russ Cox <[email protected]>
1 parent eebb9db commit 45d74aa

File tree

2 files changed

+3
-1
lines changed

2 files changed

+3
-1
lines changed

src/text/template/exec.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ func (s *state) walk(dot reflect.Value, node parse.Node) {
285285
func (s *state) walkIfOrWith(typ parse.NodeType, dot reflect.Value, pipe *parse.PipeNode, list, elseList *parse.ListNode) {
286286
defer s.pop(s.mark())
287287
val := s.evalPipeline(dot, pipe)
288-
truth, ok := isTrue(val)
288+
truth, ok := isTrue(indirectInterface(val))
289289
if !ok {
290290
s.errorf("if/with can't use %v", val)
291291
}

src/text/template/exec_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,7 @@ var execTests = []execTest{
413413
{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
414414
{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
415415
{"if nil", "{{if nil}}TRUE{{end}}", "", tVal, false},
416+
{"if on typed nil interface value", "{{if .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
416417
{"if 1", "{{if 1}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
417418
{"if 0", "{{if 0}}NON-ZERO{{else}}ZERO{{end}}", "ZERO", tVal, true},
418419
{"if 1.5", "{{if 1.5}}NON-ZERO{{else}}ZERO{{end}}", "NON-ZERO", tVal, true},
@@ -515,6 +516,7 @@ var execTests = []execTest{
515516
{"with $x int", "{{with $x := .I}}{{$x}}{{end}}", "17", tVal, true},
516517
{"with $x struct.U.V", "{{with $x := $}}{{$x.U.V}}{{end}}", "v", tVal, true},
517518
{"with variable and action", "{{with $x := $}}{{$y := $.U.V}}{{$y}}{{end}}", "v", tVal, true},
519+
{"with on typed nil interface value", "{{with .NonEmptyInterfaceTypedNil}}TRUE{{ end }}", "", tVal, true},
518520

519521
// Range.
520522
{"range []int", "{{range .SI}}-{{.}}-{{end}}", "-3--4--5-", tVal, true},

0 commit comments

Comments
 (0)