Call a method from a Go template

痞子三分冷 提交于 2019-11-27 10:44:27

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10200178/call-a-method-from-a-go-template

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!