Timur Fayzrakhmanov
Timur Fayzrakhmanov

Reputation: 19617

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

I'm trying to understand how to use call function in text/template package. Here is example:

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


I thought that call calls functions/methods, but as it turned out we can do it just by .Method arg1 arg2. So what is function call intended for?

Upvotes: 4

Views: 2394

Answers (2)

Blue Joy
Blue Joy

Reputation: 331

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

Upvotes: 1

Stephan Dollberg
Stephan Dollberg

Reputation: 34608

You need to use call if you want to call a function value.

To quote the docs (See under Functions):

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.

In this example X could look like this:

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

Upvotes: 4

Related Questions