Home >Backend Development >Golang >How to Call Go Methods Within HTML/Templates?

How to Call Go Methods Within HTML/Templates?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 03:11:09390browse

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.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn