2016-08-09 4 views
0

テンプレートHTML内で構造体配列(Mysqlからロード)を表す必要があります。 template.Execute()メソッドは応答をHTMLページとして表現するのではなく、文字列として記述します。 誰かが私を助けることができますか?私はいくつかの埋め込みgolangテンプレートを作成する方法.HTMLページとして書き出す

import (
    "fmt" 
    "log" 
    "time" 
    "net/http" 
    "database/sql" 
    _ "github.com/go-sql-driver/mysql" 
    s "strings" 
    "html/template" 
    "io/ioutil" 
) 
var p = fmt.Println 

type ListData struct{ 
    Id int 
    Os sql.NullString 
    Title string 
} 

func searchHandler(w http.ResponseWriter, r *http.Request) { 
    db,er := sql.Open("mysql","root:[email protected](localhost:3306)/collection") 
    cursor := []ListData{} 
    for rows.Next() { 
     //load data here.... 
    } 
    t, pErr := template.ParseFiles("./admin/list.html") 
    if pErr != nil { 
     panic(pErr) 
    } 
    pErr = t.Execute(w, cursor) 
    if pErr != nil { 
     http.Error(w, pErr.Error(), http.StatusInternalServerError) 
     return 
    } 
}//end of searchHandler 

func main(){ 
    p("start servlet.") 
    //other handlers 
    http.HandleFunc("/search", searchHandler) 
    log.Fatal(http.ListenAndServe(":8080", nil)) 
} 

は、このHTMLファイルにコードを行く:template.Executeは、ブラウザがレンダリングされ

enter image description here

答えて

2

をやった後

........ 
<thead> 
    <tr> 
     <th>id</th> 
     <th>os</th> 
     <th>title</th> 
    </tr> 
</thead> 
     <tbody> 
      {{range .}} 
       <tr class="success"> 
       <td>{{.Id}}</td> 
       <td>{{.Os}}</td> 
       <td>{{.Title}}</td> 
       </tr> 
      {{end}} 
     </tbody> 
     ..... 

は、HTMLページとして読み込むことができませんそれはテキストだったので、ページ。これは、サーバーからコンテンツタイプを受信しなかったためです。ヘッダーに設定する必要があります。

w.Header().Set("Content-Type", "text/html") 
+0

非常にありがとう!それは仕事です。 –

関連する問題