Add the ability to execute struct field functions
This commit is contained in:
parent
f4307541c4
commit
ce71befee8
13
salix.go
13
salix.go
@ -438,12 +438,19 @@ func (t *Template) execMethodCall(mc ast.MethodCall, local map[string]any) (any,
|
|||||||
for rval.Kind() == reflect.Pointer {
|
for rval.Kind() == reflect.Pointer {
|
||||||
rval = rval.Elem()
|
rval = rval.Elem()
|
||||||
}
|
}
|
||||||
|
// First, check for a method with the given name
|
||||||
mtd := rval.MethodByName(mc.Name.Value)
|
mtd := rval.MethodByName(mc.Name.Value)
|
||||||
if !mtd.IsValid() {
|
if mtd.IsValid() {
|
||||||
return nil, ast.PosError(mc, "no such method: %s", mc.Name.Value)
|
|
||||||
}
|
|
||||||
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
|
// execFunc executes a function call
|
||||||
func (t *Template) execFunc(fn reflect.Value, node ast.Node, args []ast.Node, local map[string]any) (any, error) {
|
func (t *Template) execFunc(fn reflect.Value, node ast.Node, args []ast.Node, local map[string]any) (any, error) {
|
||||||
|
Loading…
Reference in New Issue
Block a user