Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a method from a Go template

Let's say I have

type Person struct {   Name string } func (p *Person) Label() string {   return "This is " + p.Name } 

How can I use this method from a html/template ? I would need something like this in my template:

{{ .Label() }} 
like image 964
Blacksad Avatar asked Apr 17 '12 22:04

Blacksad


People also ask

How do you call a function in Go template?

According to the documentation, you can call any method which returns one value (of any type) or two values if the second one is of type error . In the later case, Execute will return that error if it is non-nil and stop the execution of the template. Thanks, it works !


1 Answers

Just omit the parentheses and it should be fine. Example:

package main  import (     "html/template"     "log"     "os" )  type Person string  func (p Person) Label() string {     return "This is " + string(p) }  func main() {     tmpl, err := template.New("").Parse(`{{.Label}}`)     if err != nil {         log.Fatalf("Parse: %v", err)     }     tmpl.Execute(os.Stdout, Person("Bob")) } 

According to the documentation, you can call any method which returns one value (of any type) or two values if the second one is of type error. In the later case, Execute will return that error if it is non-nil and stop the execution of the template.

like image 131
tux21b Avatar answered Sep 22 '22 13:09

tux21b