1 回答
TA贡献1876条经验 获得超5个赞
我认为最简单的方法是使用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 关注
- 85 浏览
添加回答
举报