登录
首页 >  Golang >  Go问答

如何在Go中迭代mapinterface{}来生成html表

来源:stackoverflow

时间:2024-04-02 22:39:33 254浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《如何在Go中迭代mapinterface{}来生成html表》,聊聊,希望可以帮助到正在努力赚钱的你。

问题内容

我尝试在 go 中使用 html/template 生成 html 内容。该数据实际上是来自不同 mysql 表的 select 查询的输出。

我需要以下方面的帮助

  1. 能够生成 html,但无法拆分行。如何迭代 result := []map[string]interface{}{} (我使用接口,因为列数及其类型在执行之前未知)以表格格式呈现数据?
  2. 列和行不匹配

注意:目前演示链接中的 result 包含 2 个地图,应将其视为动态。它会根据目标表而变化。

这是演示链接,其中包含与我的用例相匹配的示例数据。 https://go.dev/play/p/utl_j1iryog

下面是输出 html,它将所有值添加为单行,但也与列不匹配。

<html>
    <head>
        <meta charset="UTF-8">
        <title>My page</title>
        <style>
        table, th, td {
          border: 1px solid black;
        }
        th, td {
          padding: 10px;
        }
        </style>
    </head>
    <body>
    <table>
        <tr>
        <th>Name</th><th>Colour</th>
        </tr>
        <tr>
        <td>Red</td><td>Apple</td><td>Banana</td><td>Yellow</td>
        </tr>
    </table>
    </body>
</html>

正确答案


您可以执行以下操作:

var cols []string
var rows [][]interface{}

for key, _ := range result[0] {
    cols = append(cols, key)
}

for _, res := range result {
    vals := make([]interface{}, len(cols))
    for i, col := range cols {
        vals[i] = res[col]
    }
    rows = append(rows, vals)
}
data := struct {
    title   string
    columns []string
    rows    [][]interface{}
}{
    title:   "my page",
    columns: cols,
    rows:    rows,
}

并且 html 需要进行相应修改:

<table>
    <tr>
    {{range .Columns}}<th>{{ . }}</th>{{else}}<div><strong>no rows</strong></div>{{end}}
    </tr>
    {{- range .Rows}}
    <tr>
    {{range .}}<td>{{ . }}</td>{{end}}
    </tr>
    {{- end}}
</table>

https://go.dev/play/p/MPJOMlfQ488

请注意,在 go 中映射是无序的,因此循环 result[0] 来聚合列名将生成无序的 []string。这意味着多次查看 html 页面的用户将看到不一致的输出。如果您想避免这种情况,您可以选择使用包 sort 对列进行排序,也可以选择以某种方式保留 sql.Rows.Columns 的顺序。

到这里,我们也就讲完了《如何在Go中迭代mapinterface{}来生成html表》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>