So I have several html template files.
templates/
— head.html
— header.html
— home.html
— register.hml
head.html
{{define "head"}}
<!DOCTYPE html>
<html>
<head>
//Some meta tags and including some css/js files.
</head>
{{end}}
header.html Now here I'm using if/else statement. Based on the data, i'm showing login and register form, or "logged in as ..." message.
{{define "header"}}
<body>
<header>
//Some logo + navigation.
{{if.}}
//If there is data display:
"logged in as" {{.}}
{{else}}
//Else display a login/register form
{{end}}
</header>
{{end}}
home.html
{{define "home"}}
{{template "head" .}}
{{template "header" .}}
//some HTML code.
</body>
</html>
{{end}}
register.html Now here I'm using if statement to check if the user have failed to register and show him what the error is.
{{define "register"}}
{{template "head" .}}
{{template "header" .}}
//Displaying register form, so the user can register in the website.
{{if.}}
//If there is data, display message.
"registrain failed, reason:" {{.}}
{{end}}
</body>
</html>
{{end}}
The problem is that when I go to the register page and fail to register the error message is displayed, but also the header changes to “logged in as the error message that have to be shown only for the registration form
”
This is my Golang code:
package main
import (
"html/template"
"net/http"
)
//Caching all templates.
var tpl = template.Must(template.ParseGlob("templates/*.html"))
func main() {
//Serving static files from the assets folder like CSS and JS files.
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
//Routing and handlers
http.HandleFunc("/", indexHandler)
http.HandleFunc("/logout", logoutHandler)
http.HandleFunc("/register", registerHandler)
http.ListenAndServe(":8000", nil)
}
//My handler for the root
func indexHandler(w http.ResponseWriter, r *http.Request) {
//If there is cookie I pass the value of the cookie to the template,
//so in the website to display "logged in as: cookie value"
cookie, err := r.Cookie("username")
if err != nil {
tpl.ExecuteTemplate(w, "home", nil)
} else {
tpl.ExecuteTemplate(w, "home", cookie.Value)
}
}
//My handler for /register
func registerHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
tpl.ExecuteTemplate(w, "register", nil)
case "POST":
//validateUser() returns error if validation of the string fails.
_, err := validateUser(r.FormValue("username"))
if err != nil {
tpl.ExecuteTemplate(w, "register", err)
fmt.Sprintln(err)
} else {
//Some succes message. and redirecting to "/"
}
}
}
What’s the best way to handle this problem ?