English 中文(简体)
从Go模板中选取一种方法
原标题:Call a method from a Go template

我要说的是:

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

我如何从html/template处使用这种方法? 在我的模板中,我需要这样一些:

{{ .Label() }}
最佳回答

仅指母体,应予罚款。 例:

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

根据文件,如果第二个数值为,则你可使用任何回收价值(任何类型)或两种数值的方法。 在后一种情况下,<代码>Execute如果该错误为非本国错误,将予以退回,并停止该模板的执行。

问题回答

你们甚至能够通过如下参数来发挥职能:

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

然后在模板中书写

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

假设该模板中的人是一种变式的变体。

如果我不称职,或最近对戈模板进行了修改,但我无法利用关于数据结构的职能。 浏览器收到“can t评价外地误差”。

我得以通过使用FuncMap

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)

模板:

{{label "the label"}}

Label func:

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




相关问题
minimum work size of a goroutine [closed]

Does anyone know approximately what the minimum work size is needed in order for a goroutine to be beneficial (assuming that there are free cores for the work to be offloaded to)?

How do you get the terminal size in Go?

How do I get the terminal size in Go. In C it would look like this: struct ttysize ts; ioctl(0, TIOCGWINSZ, &ts); But how to i access TIOCGWINSZ in Go

What do you use to write Go [closed]

I know its a bit too early, but I ve been trying out Go (Google s Programming Language) and its kindof annoying to write code in gedit. So, my question: What do you use to experiment with Go?

Shared memory vs. Go channel communication

One of Go s slogans is Do not communicate by sharing memory; instead, share memory by communicating. I am wondering whether Go allows two different Go-compiled binaries running on the same machine to ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

热门标签