From e6ee26a03b79d0e8b658463bdb29349ca68e1460 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Tue, 8 Sep 2015 14:58:12 -0700 Subject: text/template: provide a way to trim leading and trailing space between actions Borrowing a suggestion from the issue listed below, we modify the lexer to trim spaces at the beginning (end) of a block of text if the action immediately before (after) is marked with a minus sign. To avoid parsing/lexing ambiguity, we require an ASCII space between the minus sign and the rest of the action. Thus: {{23 -}} < {{- 45}} produces the output 23<45 All the work is done in the lexer. The modification is invisible to the parser or any outside package (except I guess for noticing some gaps in the input if one tracks error positions). Thus it slips in without worry in text/template and html/template both. Fixes long-requested issue #9969. Change-Id: I3774be650bfa6370cb993d0899aa669c211de7b2 Reviewed-on: https://go-review.googlesource.com/14391 Reviewed-by: Andrew Gerrand --- src/text/template/exec_test.go | 29 ++++++++++++----------------- 1 file changed, 12 insertions(+), 17 deletions(-) (limited to 'src/text/template/exec_test.go') diff --git a/src/text/template/exec_test.go b/src/text/template/exec_test.go index 07ebb550ea..9fd01320c2 100644 --- a/src/text/template/exec_test.go +++ b/src/text/template/exec_test.go @@ -797,18 +797,19 @@ type Tree struct { } // Use different delimiters to test Set.Delims. +// Also test the trimming of leading and trailing spaces. const treeTemplate = ` - (define "tree") + (- define "tree" -) [ - (.Val) - (with .Left) - (template "tree" .) - (end) - (with .Right) - (template "tree" .) - (end) + (- .Val -) + (- with .Left -) + (template "tree" . -) + (- end -) + (- with .Right -) + (- template "tree" . -) + (- end -) ] - (end) + (- end -) ` func TestTree(t *testing.T) { @@ -853,19 +854,13 @@ func TestTree(t *testing.T) { t.Fatal("parse error:", err) } var b bytes.Buffer - stripSpace := func(r rune) rune { - if r == '\t' || r == '\n' { - return -1 - } - return r - } const expect = "[1[2[3[4]][5[6]]][7[8[9]][10[11]]]]" // First by looking up the template. err = tmpl.Lookup("tree").Execute(&b, tree) if err != nil { t.Fatal("exec error:", err) } - result := strings.Map(stripSpace, b.String()) + result := b.String() if result != expect { t.Errorf("expected %q got %q", expect, result) } @@ -875,7 +870,7 @@ func TestTree(t *testing.T) { if err != nil { t.Fatal("exec error:", err) } - result = strings.Map(stripSpace, b.String()) + result = b.String() if result != expect { t.Errorf("expected %q got %q", expect, result) } -- cgit v1.3-5-g9baa