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

How to Call Go Methods Within HTML/Templates?

Barbara Streisand
Release: 2024-12-10 03:11:09
Original
392 people have browsed it

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
}
Copy after login

How do we leverage this method within an HTML/template? A template such as this:

{{ .Label() }}
Copy after login

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"))
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template