From ce71befee8b7dd198947124e0ee2eff6ef6faa09 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Thu, 21 Dec 2023 21:01:15 -0800 Subject: [PATCH] Add the ability to execute struct field functions --- namespace.go | 2 +- salix.go | 13 ++++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/namespace.go b/namespace.go index 0d18337..ad01e29 100644 --- a/namespace.go +++ b/namespace.go @@ -10,7 +10,7 @@ type Namespace struct { tags map[string]Tag // WhitespaceMutations enables postprocessing to remove whitespace where it isn't needed - // to make the resulting document look better. Postprocessing is only done oncewhen the + // to make the resulting document look better. Postprocessing is only done once when the // template is parsed, so it will not affect performance. (default: true) WhitespaceMutations bool escapeHTML *bool diff --git a/salix.go b/salix.go index 9da2003..46d84a2 100644 --- a/salix.go +++ b/salix.go @@ -438,11 +438,18 @@ func (t *Template) execMethodCall(mc ast.MethodCall, local map[string]any) (any, for rval.Kind() == reflect.Pointer { rval = rval.Elem() } + // First, check for a method with the given name mtd := rval.MethodByName(mc.Name.Value) - if !mtd.IsValid() { - return nil, ast.PosError(mc, "no such method: %s", mc.Name.Value) + if mtd.IsValid() { + return t.execFunc(mtd, mc, mc.Params, local) } - return t.execFunc(mtd, mc, mc.Params, local) + // If the method doesn't exist, also check for a field storing a function. + field := rval.FieldByName(mc.Name.Value) + if field.IsValid() && field.Kind() == reflect.Func { + return t.execFunc(field, mc, mc.Params, local) + } + // If neither of those exist, return an error + return nil, ast.PosError(mc, "no such method: %s", mc.Name.Value) } // execFunc executes a function call