"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Call Go Methods Within HTML/Templates?

How to Call Go Methods Within HTML/Templates?

Published on 2025-01-29
Browse:517

How to Call Go Methods Within HTML/Templates?

Involving Go Methods in HTML/Template Interactions

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

Method Invocation in Templates

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3