text/template: allow grouping of pipelines using parentheses
Based on work by Russ Cox. From his CL:
This is generally useful but especially helpful when trying
to use the built-in boolean operators. It lets you write:
{{if not (f 1)}} foo {{end}}
{{if and (f 1) (g 2)}} bar {{end}}
{{if or (f 1) (g 2)}} quux {{end}}
instead of
{{if f 1 | not}} foo {{end}}
{{if f 1}}{{if g 2}} bar {{end}}{{end}}
{{$do := 0}}{{if f 1}}{{$do := 1}}{{else if g 2}}{{$do := 1}}{{end}}{{if $do}} quux {{end}}
The result can be a bit LISPy but the benefit in expressiveness and readability
for such a small change justifies it.
I believe no changes are required to html/template.
Fixes #3276.
R=golang-dev, adg, rogpeppe, minux.ma
CC=golang-dev
https://golang.org/cl/6482056
diff --git a/src/pkg/text/template/exec_test.go b/src/pkg/text/template/exec_test.go
index 95e0592..7f60dca 100644
--- a/src/pkg/text/template/exec_test.go
+++ b/src/pkg/text/template/exec_test.go
@@ -337,6 +337,9 @@
{"pipeline", "-{{.Method0 | .Method2 .U16}}-", "-Method2: 16 M0-", tVal, true},
{"pipeline func", "-{{call .VariadicFunc `llo` | call .VariadicFunc `he` }}-", "-<he+<llo>>-", tVal, true},
+ // Parenthesized expressions
+ {"parens in pipeline", "{{printf `%d %d %d` (1) (2 | add 3) (add 4 (add 5 6))}}", "1 5 15", tVal, true},
+
// If.
{"if true", "{{if true}}TRUE{{end}}", "TRUE", tVal, true},
{"if false", "{{if false}}TRUE{{else}}FALSE{{end}}", "FALSE", tVal, true},
@@ -524,6 +527,14 @@
return "vfunc"
}
+func add(args ...int) int {
+ sum := 0
+ for _, x := range args {
+ sum += x
+ }
+ return sum
+}
+
func stringer(s fmt.Stringer) string {
return s.String()
}
@@ -531,6 +542,7 @@
func testExecute(execTests []execTest, template *Template, t *testing.T) {
b := new(bytes.Buffer)
funcs := FuncMap{
+ "add": add,
"count": count,
"dddArg": dddArg,
"oneArg": oneArg,