从golang模板调用数组的方法
Call method of an array from golang template
所以在我的 main.go
中,我有一个结构和一个方法,我可以从内部 main.go
毫无问题地调用它们。想象一下它是这样的:
type Test struct {
val1 float32
val2 float32
}
func (t Test) callMethod() float32 {
return t.val1 / t.val2
}
我这样调用模板,作为数据,我给出了一个 Test
结构数组,如下所示:
var testvar1 Test
var testvar2 Test
var teststructs [] Test
teststructs = append(teststructs, testvar1)
teststructs = append(teststructs, testvar2)
tpl.ExecuteTemplate(w, "testpage.gohtml", teststructs)
在模板中,我试图这样调用 callMethod
{{range .}}
{{ .callMethod }}
{{end}}
但我收到以下错误:
executing "testpage.gohtml" at <.callMethod>: can't evaluate field callMethod in type main.Test
有没有人知道我做错了什么并且对此有解决方案?几个小时以来,我一直在尝试修复它,但此时我感到非常沮丧。
您的 Test
结构没有导出 fields/methods,即模板中使用的结构中的 fields/methods 必须以大写字母开头。
将方法名称更新为CallMethod
func (t Test) CallMethod() float32 {
return t.val1 / t.val2
}
和模板:
const tmpl = `
{{range .}}
{{.CallMethod}}
{{end}}
`
所以在我的 main.go
中,我有一个结构和一个方法,我可以从内部 main.go
毫无问题地调用它们。想象一下它是这样的:
type Test struct {
val1 float32
val2 float32
}
func (t Test) callMethod() float32 {
return t.val1 / t.val2
}
我这样调用模板,作为数据,我给出了一个 Test
结构数组,如下所示:
var testvar1 Test
var testvar2 Test
var teststructs [] Test
teststructs = append(teststructs, testvar1)
teststructs = append(teststructs, testvar2)
tpl.ExecuteTemplate(w, "testpage.gohtml", teststructs)
在模板中,我试图这样调用 callMethod
{{range .}}
{{ .callMethod }}
{{end}}
但我收到以下错误:
executing "testpage.gohtml" at <.callMethod>: can't evaluate field callMethod in type main.Test
有没有人知道我做错了什么并且对此有解决方案?几个小时以来,我一直在尝试修复它,但此时我感到非常沮丧。
您的 Test
结构没有导出 fields/methods,即模板中使用的结构中的 fields/methods 必须以大写字母开头。
将方法名称更新为CallMethod
func (t Test) CallMethod() float32 {
return t.val1 / t.val2
}
和模板:
const tmpl = `
{{range .}}
{{.CallMethod}}
{{end}}
`