如何使用text/template的预定义"call"功能?

How to use text/template's predefined "call" function?

我正在尝试了解如何在 text/template 包中使用 call 函数。这是示例:

type Human struct {
    Name string
}

func (h *Human) Say(str string) string {
    return str
}

func main() {
    const letter = `
    {{.Name}} wants to say {{"blabla" | .Say}}
    {{.Name}} wants try again, {{call .Say "blabla"}}.`

    var h = &Human{"Tim"}

    t := template.Must(template.New("").Parse(letter))
    err := t.Execute(os.Stdout, h)
    if err != nil {
        log.Println("executing template:", err)
    }

}
see this code in play.golang.org


我以为 call 会调用 functions/methods,但事实证明我们可以通过 .Method arg1 arg2 来完成。那么函数 call 的用途是什么?

如果要调用函数值,需要使用call

引用docs(见函数):

Thus "call .X.Y 1 2" is, in Go notation, dot.X.Y(1, 2) where Y is a func-valued field, map entry, or the like.

在此示例中 X 可能如下所示:

type X struct {
    Y func(a int, b int) int
}

https://play.golang.org/p/usia3d8STOG

    type X struct {
        Y func(a int, b int) int
    }
    x := X{Y: func(a int, b int) int {
        return a + b
    }}
    tmpl, err := template.New("test").Parse(`{{call .X.Y 1 2}}
    `)

    if err != nil {
        panic(err)
    }
    err = tmpl.Execute(os.Stdout, map[string]interface{}{"X": x})
    if err != nil {
        panic(err)
    }