1 回答

TA貢獻(xiàn)1876條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為最簡單的方法是使用html/template包。text/template的文檔解釋了語法,以防您不熟悉模板引擎。
像這樣(游樂場鏈接):
package main
import (
"html/template"
"os"
)
const tplStr = `<table>
<thead>
<tr>
<th>Teacher</th>
<th>Student</th>
<th>Blue Pens</th>
<th>Red Pens</th>
</tr>
</thead>
<tbody>
{{range $teacher, $rows := . }}
{{ $first := true }}
{{ range $student, $colors := . }}
<tr>
<td>{{ if $first }}{{ $first = false }}{{ $teacher }}{{ end }}</td>
<td>{{ $student }}</td>
<td>{{ $colors.Blue }}</td>
<td>{{ $colors.Red }}</td>
</tr>
{{ end }}
{{ end }}
</tbody>
</table>`
type color struct {
Blue int
Red int
}
func fetchData() map[string]map[string]color {
return map[string]map[string]color{
"joe": {
"alex": {
Blue: 3,
Red: 6,
},
"may": {
Blue: 2,
Red: 6,
},
},
"jena": {
"fred": color{
Blue: 1,
Red: 2,
},
},
}
}
func main() {
tpl, err := template.New("table").Parse(tplStr)
if err != nil {
panic(err)
}
err = tpl.Execute(os.Stdout, fetchData())
if err != nil {
panic(err)
}
}
- 1 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報(bào)