Skip to content

Commit

Permalink
tpl/collections: Fix apply with namespaced template funcs
Browse files Browse the repository at this point in the history
We changed the signature to `func(...interface{}) (interface{}, error)` some time ago, but sadly we had no test for this for `apply`. Now we do.

Fixes gohugoio#9393
  • Loading branch information
bep committed Jan 17, 2022
1 parent 348d300 commit 2655739
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
19 changes: 17 additions & 2 deletions hugolib/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,6 @@ complex: 80: 80

// Issue 7528
func TestPartialWithZeroedArgs(t *testing.T) {

b := newTestSitesBuilder(t)
b.WithTemplatesAdded("index.html",
`
Expand All @@ -483,7 +482,6 @@ X123X
X123X
X123X
`)

}

func TestPartialCached(t *testing.T) {
Expand Down Expand Up @@ -757,3 +755,20 @@ This is single main
`,
)
}

// Issue 9393.
func TestApplyWithNamespace(t *testing.T) {
b := newTestSitesBuilder(t)

b.WithTemplates(
"index.html", `
{{ $b := slice " a " " b " " c" }}
{{ $a := apply $b "strings.Trim" "." " " }}
a: {{ $a }}
`,
).WithContent("p1.md", "")

b.Build(BuildCfg{})

b.AssertFileContent("public/index.html", `a: [a b c]`)
}
14 changes: 12 additions & 2 deletions tpl/collections/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,25 @@ func (ns *Namespace) lookupFunc(fname string) (reflect.Value, bool) {

ss := strings.SplitN(fname, ".", 2)

// namespace
// Namespace
nv, found := ns.lookupFunc(ss[0])
if !found {
return reflect.Value{}, false
}

fn, ok := nv.Interface().(func(...interface{}) (interface{}, error))
if !ok {
return reflect.Value{}, false
}
v, err := fn()
if err != nil {
panic(err)
}
nv = reflect.ValueOf(v)

// method
m := nv.MethodByName(ss[1])
// if reflect.DeepEqual(m, reflect.Value{}) {

if m.Kind() == reflect.Invalid {
return reflect.Value{}, false
}
Expand Down

0 comments on commit 2655739

Please sign in to comment.