Home >Backend Development >Golang >How to Call Go Methods Within HTML/Templates?
Let's consider the following:
type Person struct { Name string } func (p *Person) Label() string { return "This is " + p.Name }
How do we leverage this method within an HTML/template? A template such as this:
{{ .Label() }}
Avoid using parentheses when calling methods in templates. For instance:
tmpl, err := template.New("").Parse(`{{.Label}}`) if err != nil { log.Fatalf("Parse: %v", err) } tmpl.Execute(os.Stdout, Person("Bob"))
This approach adheres to the documentation guidelines, which specify that methods returning a single value (or a value and an error) can be called within templates. If an error occurs during execution, it will be returned and the template execution will cease.
The above is the detailed content of How to Call Go Methods Within HTML/Templates?. For more information, please follow other related articles on the PHP Chinese website!