Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid rendering cycle in partials #15

Merged
merged 1 commit into from
Aug 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion mustache.go
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,16 @@ type partialNode struct {
func (p *partialNode) render(t *Template, w *writer, c ...interface{}) error {
w.tag()
if template, ok := t.partials[p.name]; ok {
template.partials = t.partials

// We can avoid cycles by removing this node's template from the lookup
// before we render
template.partials = make(map[string]*Template)
for k, v := range t.partials {
if k != p.name {
template.partials[k] = v
}
}

err := template.render(w, c...)
if err != nil {
if !t.silentMiss {
Expand Down
31 changes: 31 additions & 0 deletions mustache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,34 @@ func TestSectionTestValue(t *testing.T) {
}

}

func TestPartialsCannotCycle(t *testing.T) {
innerTemplate := New(Name("inner"))
err := innerTemplate.Parse(strings.NewReader(`I am the inner.{{>outer}}`))
if err != nil {
t.Error(err)
}

outerTemplate := New(Name("outer"))
err = outerTemplate.Parse(strings.NewReader(`I am the outer.{{>inner}}`))
if err != nil {
t.Error(err)
}

mainTemplate := New(Partial(outerTemplate), Partial(innerTemplate))
err = mainTemplate.Parse(strings.NewReader(`{{>outer}}`))
if err != nil {
t.Error(err)
}

var output bytes.Buffer
err = mainTemplate.Render(&output)
if err != nil {
t.Error(err)
}

expected := `I am the outer.I am the inner.`
if output.String() != expected {
t.Errorf("expected %q got %q", expected, output.String())
}
}
Loading