Golang模板上的函数调用在单个结构体上失败了。

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

Golang function call on template fails on a single struct

问题

我有以下代码:

func (w *Warehouse) GetId() string {
  return w.Id.Hex()
}

在多个视图中运行得很好:

{{ range .Data }}
   <tr>
   <td>{{ .Name }}</td>
   <td>{{ .City }}</td>
   <td>{{ .Manager }}</td>
   <td><a class="blue" href="/warehouse/show/{{ .GetId }}">view</a></td>
   </tr>
{{ end }}

在单个展示仓库的视图中,我尝试了以下代码,但是当使用.Data.GetId时失败了,而.Data.Name可以正确返回名称:

{{ .Data.GetId }}

你有什么想法,我在这里漏掉了什么?

英文:

i have following code

func (w *Warehouse) GetId() string {
  return w.Id.Hex()
}

view multiple works perfect

{{ range .Data }}
   &lt;tr&gt;
   &lt;td&gt;{{ .Name }}&lt;/td&gt;
   &lt;td&gt;{{ .City }}&lt;/td&gt;
   &lt;td&gt;{{ .Manager }}&lt;/td&gt;
   &lt;td&gt;&lt;a class=&quot;blue&quot; href=&quot;/warehouse/show/{{ .GetId }}&quot;&gt;view&lt;/a&gt;&lt;/td&gt;
   &lt;/tr&gt;
{{ end }}

in single show warehouse i do this but that fails while .Data.Name return the name correctly

{{ .Data.GetId }}

any idea what i am missing here?

答案1

得分: 1

问题是我需要像这样创建我的结构体的实例:

var warehouse = new(models.Warehouse) // 正常工作

而不是

var warehouse models.Warehouse // 失败
英文:

problem is that i needed to make instance of my struct like this

var warehouse = new(models.Warehouse) // works

instead of

var warehouse models.Warehouse // fails

答案2

得分: 0

根据你的代码,Data 是一个数组或切片,它没有 GetId() 方法。

英文:

According to your code .Data is array or slice. It does not have GetId() method

huangapple
  • 本文由 发表于 2014年7月25日 17:56:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/24952983.html
匿名

发表评论

匿名网友

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

确定