How to iterate through a list in a Go template

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

How to iterate through a list in a Go template

问题

我有一个从数据库中检索一堆推文(Tweet 类型)并将它们传递给模板的函数。在模板中,我需要循环遍历数组,并打印从数据库中检索到的每个推文的 message 字段。下面的模板根本没有显示任何内容。

我该如何指示我正在循环遍历一个 Tweet 类型的数组,并打印每个推文的消息?

func Root(w http.ResponseWriter, r *http.Request) {
  tweets := []*Tweet{}
  t := template.Must(template.New("main").ParseFiles("main.html"))

  err := Orm.Find(&tweets)
  if err != nil {
    fmt.Println("err", err)
    return
  }
  t.ExecuteTemplate(w, "main.html", tweets)
}

main.html

{{range .Tweet}}  
  status: {{.message}}
{{end}}
英文:

I have a function that retrieves a bunch of Tweets (of type Tweet) from a database and passes them to a template. In the template, I have to loop through the array and print the message field for each tweet retrieved from the db. The template below doesn't display anything at all.

How do I indicate that I'm looping through an array of type Tweet and then print the message for each?

    func Root(w http.ResponseWriter, r *http.Request) {
      tweets := []*Tweet{}
	  t := template.Must(template.New("main").ParseFiles("main.html"))
	
	  err := Orm.Find(&tweets)
	  if err != nil {
		fmt.Println("err", err)
		return
	  }
	  t.ExecuteTemplate(w, "main.html", tweets)
    }

main.html

 {{range .Tweet}}  
      status: {{.message}}
 {{end}}

答案1

得分: 10

你这里有两个错误。

  1. .Tweet 是从哪里来的?你给模板引擎传递了 tweets,一个 []*Tweet 类型的输入,所以 . 是一个切片,没有 Tweet 字段或键。

  2. .message 没有被导出,只有导出的字段才能在模板中使用。


最终结果:

{{range .}}
    状态:{{.Message}}
{{end}}

记得修改你的 Tweet 类型来使用新的字段名。

英文:

You have two errors here.

  1. Where does .Tweet come from? You gave the template engine tweets, a []*Tweet as the input so . is a slice and has no Tweet field or key.

  2. .message is not exported, only exported fields may be used in a template.


The end result:

{{range .}}
    status: {{.Message}}
{{end}}

Remember to modify your Tweet type to use the new field name.

huangapple
  • 本文由 发表于 2014年8月9日 22:21:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/25219510.html
匿名

发表评论

匿名网友

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

确定