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は、ブラウザがレンダリングされ
非常にありがとう!それは仕事です。 –