douba9020 2019-06-27 13:11
浏览 14
已采纳

我想获取数据会话和标题,但从数据库中检索数据时它不在循环中

I have taken all the data from the database then the data is in a loop. Apart from the looping that happened, I want to insert other data such as Session, and Title. Then I put it into the template.

I have a guess for using struct or slice, but I can't find a solution after learning it.

type Sekolah struct {
  Id int
  Nama string
  Alamat string
  Telp string 
}

I have a struct like the one above, then I make the handle function

http.HandleFunc("/sekolah", func(w http.ResponseWriter, r *http.Request) {

//THIS IS THE DATA I WANT TO SERVE IN TEMPLATE
var title := "Some Title"
var session := "MySession"

    db, errdb := sql.Open("postgres", koneksi)
    if errdb != nil {
        fmt.Println(errdb)
    }

    rows, err := db.Query("SELECT id, nama, alamat, telp FROM public.m_sekolah")
    if err != nil {
        fmt.Println(err)
        http.Error(w, "there was an error", http.StatusInternalServerError)
        return
    }

    var id int
    var nama string
    var alamat string
    var telp string
    var sk []Sekolah

    for rows.Next(){
        err = rows.Scan(&id, &nama, &alamat, &telp)
        if err != nil {
            fmt.Println(err)
            http.Error(w, "There was an error", http.StatusInternalServerError)
            return
        }

        sk = append(sk, Sekolah{Id: id, Nama: nama, Alamat: alamat, Telp: telp})
    }

    err = tmpl.ExecuteTemplate(w, "data_sekolah", sk)
    if err != nil {
        fmt.Println(err)
    }
})

I want to enter Title and Session data into the SK data but do not participate in the loop, then I want to paste it into the template. Can anyone help me?

  • 写回答

1条回答 默认 最新

  • dqsp60748 2019-06-28 06:04
    关注

    Put all your data in a map and pass the map to the template. Something like this.

    datamap := make(map[string]interface{})
    datamap["title"] = <your title>
    datamap["session"] = <your session>
    datamap["sk"] = <your sk array>
    

    Then, on the template, access the fields like this.

    <p>{{.title}}</p>
    <p>{{.session}}</p>
    {{range .sk}}
    <p>{{.Nama}}</p>
    {{end}}
    

    Note. This code is untested but i have solved your exact problem on a previous project of mine. Cheers

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭