我一直在网上搜索,找不到太多关于在 golang 中发布到 html 模板和表单的信息。这是我的尝试
我的错误 不能使用 "html/template".HTML("login") (类型 "html/template".HTML) 作为 "html/template".New("foo").Parse 参数中的类型字符串
我想将一个值传递给 html 文件中的 {{.ErrorMessage}}
我的 HTML (login.html)
{{ define "content"}}
<h2> {{.ErrorMessage}}</h2>
form action="/login" method="POST">
Username:input type="username" name="username">
Password:input type="password" name="password">
input type="submit" value="Submit">
/form>
{{end}}
{{define "extra_head"}} <title>Title</title>{{end}}
{{define "nav"}}{{end}}
{{define "extra_footer"}}<footer>copyright@xyz.com</footer>{{end}}
{{template "_layout.html" .}}
MAIN.G0
package main
import (
"net/http"
"ere.com/handlers"
)
func main() {
http.HandleFunc("/register", handlers.RegisterHandler) // setting router rule
http.HandleFunc("/sucess", handlers.RegisterSucessHandler)
http.HandleFunc("/login", handlers.LoginHandler)
http.HandleFunc("/update", handlers.UpdateHandler)
http.HandleFunc("/logout", handlers.LogoutHandler)
http.HandleFunc("/header", handlers.HeaderHandler)
if err := http.ListenAndServe(":8181", nil); err != nil {
//log.Fatal("http.ListenAndServe: ", err)
}
}
处理程序 int
package handlers
import (
"html/template"
)
func GetTemplate(name string) *template.Template{
tmpl := template.Must(template.ParseFiles(
"frontend/templates/_layout.html",
"frontend/templates/" + name + ".html",
))
return tmpl
}
登录处理程序
type viewModel struct {
Id bson.ObjectId
Email string
Password string
FirstName string
LastName string
ErrorMessage string
}
func LoginHandler (response http.ResponseWriter, request *http.Request) {
viewModel:=viewmodels.RegisterViewModel{}
if (request.Method == "POST") {
request.ParseForm()
user := models.User{}
user.Email = request.Form.Get("username")
user.Password = request.Form.Get("password")
boolUser, userID := user.FindUserDB()
if (boolUser != true) {
viewModel.ErrorMessage = "incorrect username or password"
//need help here
t, err := template.New("foo").Parse(template.HTML("login"))
err = t.ExecuteTemplate(response, "T", viewModel)
err := GetTemplate("login").Execute(response, nil, )
if err != nil {
panic(err)
}
}else {
setSession(userID, response)
http.Redirect(response, request, "/update", 302)
}
}else {
err := GetTemplate("login").Execute(response, nil,)
if err != nil {
panic(err)
}
}