dqczgtem06898 2017-06-08 16:28
浏览 51
已采纳

如何在Golang中将列表传递给模板

I want to use a query which looks like

rows:= db.Query("SELECT * FROM names")

var name string

for rows.Next() {
    rows.Scan(&name)
}

//There should be a map

t.Execute(w,p)

I want to shape up this to list all names in template like

{{range .name}}
{{.}}
{{end}}

How can i exactly do that?

  • 写回答

1条回答 默认 最新

  • dousou3027 2017-06-08 20:39
    关注

    Something Like This?

    rows, err := db.Query("SELECT name FROM names")
    if err != nil {
        // Handle error
    }
    
    names := make([]string, 0)
    
    for rows.Next() {
        var name string
    
        err := rows.Scan(&name)
        if err != nil {
            // Handle error
            continue
        }
    
        names = append(names, name)
    }
    
    t := template.New("index")
    t, _ = t.Parse(`{{range .}}{{.}} {{end}}`)
    t.Execute(w, names)
    

    Things to Note

    • You should generally avoid using * in your sql queries to make it clear what fields are being selected
    • If any fields in your database table can be NULL, then use sql.NullBool, sql.NullFloat64, sql.NullInt64 or sql.NullString to avoid possible errors

    Possible Output

    Bob Jim David Henry Jerry 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 h3.6m 人类行为预测论文复现
  • ¥50 wordpress项目注册报失败刷新后其实是成功状态,请求排查原因
  • ¥20 linxu服务器僵尸进程不释放,代码如何修改?
  • ¥15 pycharm激活不成功
  • ¥40 如果update 一个列名为参数的value
  • ¥15 基于51单片机的水位检测系统设计中LCD1602一直不显示
  • ¥15 OCS2安装出现问题,请大家给点意见
  • ¥15 ros小车启动launch文件报错
  • ¥15 vs2015到期想登陆但是登陆不上
  • ¥15 IPQ5018制作烧录固件,boot运行失败(操作系统-linux)(相关搜索:操作系统)(相关搜索:操作系统)