【问题标题】:How to use text/template's predefined "call" function?如何使用文本/模板的预定义“调用”功能?
【发布时间】:2015-07-04 07:14:52
【问题描述】:

我正在尝试了解如何在 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 的功能是什么?

【问题讨论】:

    标签: go template-engine


    【解决方案1】:

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

    引用docs(参见函数下方):

    因此,“call .X.Y 1 2”在 Go 表示法中是 dot.X.Y(1, 2),其中 Y 是 func 值字段、映射条目等。

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

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

    【讨论】:

    • 对不起,但它什么也没告诉我。我已经阅读了 3 次.. 你能举个例子吗? “功能价值”是什么意思?
    • @TimurFayzrakhmanov 添加了 X 的外观示例。
    【解决方案2】:

    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)
        }
    

    【讨论】:

      猜你喜欢
      • 2020-02-11
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2018-10-23
      • 1970-01-01
      • 2019-10-26
      相关资源
      最近更新 更多