Skip to content

Commit

Permalink
fix(parser): block trimming is broken with consecutive blocks
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolaLohinski committed May 11, 2024
1 parent abb2156 commit e7451de
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
14 changes: 13 additions & 1 deletion parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package parser
import (
"fmt"
"io"
"regexp"
"strings"

"github.com/nikolalohinski/gonja/v2/config"
Expand All @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
32 changes: 32 additions & 0 deletions tests/integration/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
})
})

0 comments on commit e7451de

Please sign in to comment.