From e7451defd42009c152bcbb21640295b0d5eda21b Mon Sep 17 00:00:00 2001 From: NikolaLohinski Date: Sat, 11 May 2024 22:39:06 +0200 Subject: [PATCH] fix(parser): block trimming is broken with consecutive blocks --- parser/parser.go | 14 +++++++++++++- tests/integration/config_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/parser/parser.go b/parser/parser.go index 4292afa..f753ea4 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -3,6 +3,7 @@ package parser import ( "fmt" "io" + "regexp" "strings" "github.com/nikolalohinski/gonja/v2/config" @@ -11,6 +12,10 @@ import ( "github.com/nikolalohinski/gonja/v2/tokens" ) +var ( + lineReturnWithOnlyWitheSpace = regexp.MustCompile("^(\n|\r)[ \t]*$") +) + type ControlStructureGetter interface { Get(name string) (ControlStructureParser, bool) } @@ -218,7 +223,14 @@ func (p *Parser) parseDocElement() (nodes.Node, error) { case tokens.VariableBegin: return p.ParseExpressionNode() case tokens.BlockBegin: - return p.ParseControlStructureBlock() + node, err := p.ParseControlStructureBlock() + if err != nil { + return node, err + } + if data := p.Current(tokens.Data); data != nil && p.Peek(tokens.BlockBegin) != nil && lineReturnWithOnlyWitheSpace.MatchString(data.Val) { + p.Consume() // Consume whitespace + } + return node, err } return nil, p.Error("Unexpected token (only HTML/tags/filters in templates allowed)", t) } diff --git a/tests/integration/config_test.go b/tests/integration/config_test.go index 9a0c771..e8c6e69 100644 --- a/tests/integration/config_test.go +++ b/tests/integration/config_test.go @@ -268,4 +268,36 @@ var _ = Context("config", func() { }) }) }) + Context("https://github.com/NikolaLohinski/gonja/issues/18", func() { + BeforeEach(func() { + (*configuration).TrimBlocks = true + *loader = loaders.MustNewMemoryLoader(map[string]string{ + *identifier: heredoc.Doc(` + {% if one %} + - 1 + {% endif %} + {% if two %} + - 2 + {% endif %} + {% if three %} + - 3 + {% endif %}`), + }) + (*environment).Context.Set("one", true) + (*environment).Context.Set("two", true) + (*environment).Context.Set("three", true) + }) + + It("should return the expected rendered content", func() { + By("not returning any error") + Expect(*returnedErr).To(BeNil()) + By("returning the expected result") + expected := heredoc.Doc(` + - 1 + - 2 + - 3 + `) + AssertPrettyDiff(expected, *returnedResult) + }) + }) })