从Go模板中调用一个方法

huangapple go评论84阅读模式
英文:

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() }}
英文:

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

得分: 78

只需省略括号,就可以了。示例:

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

根据文档,您可以调用任何返回一个值(任意类型)或两个值(第二个值为error类型)的方法。在后一种情况下,如果Execute返回的错误不为nil,则会返回该错误并停止模板的执行。

英文:

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

得分: 46

你甚至可以像下面这样向函数传递参数

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

然后在模板中写入

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

假设模板中的person是传递给模板的类型为Person的变量。

英文:

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.

答案3

得分: -1

不确定是我个人的无能还是Go模板的最近变化,但我无法访问传递给Execute的数据结构上的函数。总是收到“无法评估字段”的错误。

我通过使用FuncMap来解决了这个问题。

示例:

temp := template.New("templatename.gohtml")
temp.Funcs(
	template.FuncMap{
		"label": Label,
	},
)
temp, err := temp.ParseFiles(
	"templatename.gohtml",
)
if err != nil {
	log.Fatal("解析模板错误", err)
}

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

在模板中:

{{label "标签"}}

Label函数:

func Label(param string) string {
  ...
}
英文:

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

huangapple
  • 本文由 发表于 2012年4月18日 06:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/10200178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定