Skip to content

Commit 5c7fad2

Browse files
committed
tpl/collections: Fix apply to work with built-in funcs like len
Fixes #13418
1 parent 700bb78 commit 5c7fad2

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

‎tpl/collections/apply.go‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ func (ns *Namespace) Apply(ctx context.Context, c any, fname string, args ...any
6464
}
6565
}
6666

67+
var typeOfReflectValue = reflect.TypeOf(reflect.Value{})
68+
6769
func applyFnToThis(ctx context.Context, fn, this reflect.Value, args ...any) (reflect.Value, error) {
6870
num := fn.Type().NumIn()
6971
if num > 0 && hreflect.IsContextType(fn.Type().In(0)) {
@@ -91,7 +93,11 @@ func applyFnToThis(ctx context.Context, fn, this reflect.Value, args ...any) (re
9193
}*/
9294

9395
for i := range num {
94-
// AssignableTo reports whether xt is assignable to type targ.
96+
// Go's built-in template funcs (e.g. len) use reflect.Value as argument type.
97+
if fn.Type().In(i) == typeOfReflectValue && n[i].Type() != typeOfReflectValue {
98+
n[i] = reflect.ValueOf(n[i])
99+
}
100+
95101
if xt, targ := n[i].Type(), fn.Type().In(i); !xt.AssignableTo(targ) {
96102
return reflect.ValueOf(nil), errors.New("called apply using " + xt.String() + " as type " + targ.String())
97103
}

‎tpl/collections/collections_integration_test.go‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,21 @@ baseURL = 'http://example.com/'
3939
`)
4040
}
4141

42+
func TestApplyBuiltInIssue13418(t *testing.T) {
43+
t.Parallel()
44+
45+
files := `
46+
-- hugo.toml --
47+
baseURL = 'http://example.com/'
48+
-- layouts/home.html --
49+
len: {{ apply (slice "hello") "len" "." }}
50+
not: {{ apply (slice "hello") "not" "." }}
51+
`
52+
b := hugolib.Test(t, files)
53+
54+
b.AssertFileContent("public/index.html", "len: [5]", "not: [false]")
55+
}
56+
4257
// Issue 9865
4358
func TestSortStable(t *testing.T) {
4459
t.Parallel()

0 commit comments

Comments
 (0)