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.
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