0

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?

  • Possible duplicate of [Go Template : Use nested struct's field and {{range}} tag together](https://stackoverflow.com/questions/42022392/go-template-use-nested-structs-field-and-range-tag-together) – georgeok Jun 27 '19 at 13:24

1 Answers1

0

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