Home >Backend Development >Golang >How Do I Call a Go Method from Within a Template?
Consider the following code:
type Person struct { Name string } func (p *Person) Label() string { return "This is " + p.Name }
To use this method in an HTML template, you would typically expect syntax similar to the following:
{{ .Label() }}
However, in Go templates, the parentheses can be omitted:
{{ .Label }}
For instance, given the following code:
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")) }
The template will generate the output:
This is Bob
As per the Go template documentation, you can invoke any method that returns a single value or two values, where the second value is an error. If the method returns an error, Execute will return the error and halt template execution.
The above is the detailed content of How Do I Call a Go Method from Within a Template?. For more information, please follow other related articles on the PHP Chinese website!