Call a method from a Go template

后端 未结 2 1687
情歌与酒
情歌与酒 2020-12-13 09:00

Let\'s say I have

type Person struct {
  Name string
}
func (p *Person) Label() string {
  return \"This is \" + p.Name
}

How can I use thi

相关标签:
2条回答
  • 2020-12-13 09:56

    Just omit the parentheses and it should be fine. Example:

    package main
    
    import (
        "html/template"
        "log"
        "os"
    )
    
    type Person string
    
    func (p Person) Label() string {
        return "This is " + string(p)
    }
    
    func main() {
        tmpl, err := template.New("").Parse(`{{.Label}}`)
        if err != nil {
            log.Fatalf("Parse: %v", err)
        }
        tmpl.Execute(os.Stdout, Person("Bob"))
    }
    

    According to the documentation, you can call any method which returns one value (of any type) or two values if the second one is of type error. In the later case, Execute will return that error if it is non-nil and stop the execution of the template.

    0 讨论(0)
  • 2020-12-13 10:02

    You can even pass parameters to function like follows

    type Person struct {
      Name string
    }
    func (p *Person) Label(param1 string) string {
      return "This is " + p.Name + " - " + param1
    }
    

    And then in the template write

    {{with person}}
        {{ .Label "value1"}}
    {{end}}
    

    Assuming that the person in the template is a variable of type Person passed to Template.

    0 讨论(0)
提交回复
热议问题