Calling Methods from Go Templates
In Go, you can define methods for custom types, allowing you to operate on those types in a more organized manner. When working with HTML templates, it's often useful to access these methods from within the template itself.
Question:
Consider the following:
type Person struct { Name string } func (p *Person) Label() string { return "This is " + p.Name }
How would you utilize the Label() method within an HTML template?
Answer:
To call a method from a Go template, simply omit the parentheses. In this case, the template would look like:
{{ .Label }}
This will call the Label() method and insert its return value into the template.
Here's a full 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")) }
Additional Note:
According to the Go documentation, any method that returns one value of any type or two values, with the second being of type error, can be called from a template.
The above is the detailed content of How to Call Go Methods from HTML Templates?. For more information, please follow other related articles on the PHP Chinese website!