我是新手,很难渲染模板。
这是我要生成模板的功能:
base.html
//Render templates for the given name, template definition and data object
func renderTemplate(w http.ResponseWriter, name string, template string, viewModel interface{}) {
// Ensure the template exists in the map.
tmpl, ok := templates[name]
if !ok {
http.Error(w, "The template does not exist.", http.StatusInternalServerError)
}
err := tmpl.ExecuteTemplate(w, template, viewModel)
if err != nil {
log.Printf("temlate error here")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func EditNote(w http.ResponseWriter, r *http.Request) {
//var viewModel models.EditChnl
vars := mux.Vars(r)
//ch := bson.M{"id": "Ale"}
title := vars["title"]
log.Printf("%v\n", title)
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
session.SetMode(mgo.Monotonic, true)
c := session.DB("tlgdb").C("chnls")
log.Printf("title is %s \n", title)
var result []models.Chnl
err = c.Find(bson.M{"title": "xxx"}).All(&result)
log.Printf("%v\n", result)
if err != nil {
log.Printf("doc not found")
log.Fatal(err)
return
}
renderTemplate(w, "edit", "base", result)
}
这里是模板:
{{define "base"}}
<html>
<head>
{{template "head" .}}
</head>
<body>
{{template "body" .}}
</body>
</html>
{{end}}
编辑.thml
{{define "head"}}<title>Edit Note</title>{{end}}
{{define "body"}}
<h1>Edit Note</h1>
<form action="/chnls/update/{{.Title}}" method="post">
<p>Title:<br> <input type="text" value="{{.Title}}" name="title"></p>
<p>Description:<br> <textarea rows="4" cols="50" name="description">{{.Description}}</textarea> </p>
<p><input type="submit" value="submit"/></p>
</form>
{{end}}
要渲染的对象是:
type Chnl struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Title string
Description string
CreatedOn time.Time
Creator string
Visits int
Score int
}
我试图渲染的对象存在于 mongodb 中,我可以在控制台中打印出来:
[{ObjectIdHex("56cc4493bc54f4245cb4d36b") sometitle blabla 2016-02-23 12:37:55.972 +0100 CET blabla 0 0}]
但是我收到此错误:
temlate error here
http: multiple response.WriteHeader calls
我想知道这里出了什么问题以及如何解决?