doukuiqian5345
2019-03-30 23:38
浏览 488
已采纳

从golang模板调用数组的方法

So in my main.go I have a struct and a method that I can call from inside main.go without a problem. Imagine it being like this:

type Test struct {
    val1 float32
    val2 float32
}

func (t Test) callMethod() float32 {
    return t.val1 / t.val2
}

I am calling the template like this and as data I am giving an array of the Test structs, like this:

var testvar1 Test
var testvar2 Test
var teststructs [] Test
teststructs = append(teststructs, testvar1)
teststructs = append(teststructs, testvar2)
tpl.ExecuteTemplate(w, "testpage.gohtml", teststructs)

Inside the template I am trying to call the callMethod like this

{{range .}}
    {{ .callMethod }}
{{end}}

But I am getting the following error:

executing "testpage.gohtml" at <.callMethod>: can't evaluate field callMethod in type main.Test

Has anyone an Idea what I am doing wrong and has a solution for this? I am trying to fix it since many hours and I am so frustrated at this point.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanbimo7212 2019-03-31 02:03
    已采纳

    Your Teststruct has no exported fields/methods, i.e. fields/methods within the struct that are used within the template have to start with a capital letter.

    Update the method name to CallMethod

    func (t Test) CallMethod() float32 {
        return t.val1 / t.val2
    }
    

    and the template:

    const tmpl = `
    {{range .}}
       {{.CallMethod}}
    {{end}}
    `
    

    see the code https://play.golang.org/p/Vud7ipJ_Vyr

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题