猿问

HTML 转发器组

我正在尝试创建一个包含表格的 HTML 模板。表中的每一行都应代表我拥有的结构并包含该结构中的值。

我发现的唯一相关参考是:golang template - how to render templates?

不同之处在于我事先不知道表中的行数,因此我需要能够遍历我拥有的结构的动态列表,并且对于每个这样的结构,将其值填充到表示一行的模板中并将该行添加到代表表的父模板中。

谁能告诉我如何做到这一点?也欢迎任何其他方法。


红颜莎娜
浏览 521回答 1
1回答

肥皂起泡泡

我想你只是在寻找{{range}},对吧?例如package mainimport "log"import "os"import "html/template"type Highscore struct {&nbsp; &nbsp; Name&nbsp; string&nbsp; &nbsp; Score int}func main() {&nbsp; &nbsp; const tpl = `<ol>{{range .}}&nbsp; &nbsp; <li>{{.Name}} - {{.Score}}</li>{{end}}</ol>`&nbsp; &nbsp; scores := []Highscore{&nbsp; &nbsp; &nbsp; &nbsp; Highscore{"Steve", 50},&nbsp; &nbsp; &nbsp; &nbsp; Highscore{"Jim", 40},&nbsp; &nbsp; }&nbsp; &nbsp; scoreTemplate, err := template.New("scores").Parse(tpl)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }&nbsp; &nbsp; err = scoreTemplate.Execute(os.Stdout, scores)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal(err)&nbsp; &nbsp; }}
随时随地看视频慕课网APP

相关分类

Go
我要回答