I'm writing a web server in Go and was asking myself, what the conventional way of conditionally hiding a part of an HTML page is. If I wanted a "sign in" button only to show up, when the user is NOT logged in, how would I achieve something like this? Is it achieved with template engines or something else?
Thank you for taking the time to read and answer this :)
you just have to give a struct to your template and manage the rendering inside it.
Here is a working exemple to test:
package main
import (
"html/template"
"net/http"
)
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":8000", nil)
}
type User struct {
Name string
}
func helloHandler(w http.ResponseWriter, r *http.Request) {
t := template.New("logged exemple")
t, _ = t.Parse(`
<html>
<head>
<title>Login test</title>
</head>
<body>
{{if .Logged}}
It's me {{ .User.Name }}
{{else}}
-- menu --
{{end}}
</body>
</html>
`)
// Put the login logic in a middleware
p := struct {
Logged bool
User *User
}{
Logged: true,
User: &User{Name: "Mario"},
}
t.Execute(w, p)
}
To manage the connexion you can use http://www.gorillatoolkit.org/pkg/sessions with https://github.com/codegangsta/negroni and create the connection logic inside a middleware.
Simply start session on user login .Set the necessary values in session and then hide the html u want with if tag in javascript using session. Its very simple and best way to solve this type of problems.
You might try something like this
<?php
if($_SESSION['user']){}else{
echo '<button onclick="yourfunction();">sign in</button>';
}
?>
Thus, if they aren't logged in, this'll show up.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.