go - 如何使用text/template预定义的 "call"函数?

标签 go template-engine

我试图了解如何在 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 调用函数/方法,但事实证明我们可以通过 .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
}

关于go - 如何使用text/template预定义的 "call"函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31218030/

相关文章:

go - 如何在不返回的情况下更改函数中的 slice ?

arrays - 迭代结构类型的数组

go - 在 Cadence 工作流程中的循环内调用相同的事件

javascript - 相思木- Handlebars : Unable to render view: The partial could not be found

freemarker - freemarker 中的串联字符串

bash - 使用 bash 脚本从模板创建新文件

sockets - go 中的套接字需要写缓冲区吗?

go - golangs os.Stat 是否打开文件?

php - Savant3 模板引擎错误,检查 fetch() 结果

template-engine - react .js : Passing values inside attributes