Blacksad
Blacksad

Reputation: 15442

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

Upvotes: 64

Views: 54567

Answers (3)

Sam Berry
Sam Berry

Reputation: 7844

Unsure if it is incompetence on my part or a recent change in Go templates, but I am unable to access functions on the data struct passed into Execute. Always receive "can't evaluate field" error.

I was able to get this working by using FuncMap instead.

Example:

temp := template.New("templatename.gohtml")
temp.Funcs(
    template.FuncMap{
        "label": Label,
    },
)
temp, err := temp.ParseFiles(
    "templatename.gohtml",
)
if err != nil {
    log.Fatal("Error parsing template", err)
}

err = temp.Execute(os.Stdout, nil)

In template:

{{label "the label"}}

Label func:

func Label(param string) string {
  ...
}

Upvotes: -2

tux21b
tux21b

Reputation: 94739

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.

Upvotes: 85

Usman Qadri
Usman Qadri

Reputation: 519

You can even pass parameters to function like follows

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

And then in the template write

{{with person}}
    {{ .Label "value1"}}
{{end}}

Assuming that the person in the template is a variable of type Person passed to Template.

Upvotes: 51

Related Questions