drcomwc134525 2015-07-20 20:14
浏览 166
已采纳

如果用户已登录,则隐藏HTML内容

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 :)

  • 写回答

3条回答 默认 最新

  • dqc19941228 2015-07-20 22:51
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?