如果用户登录,则隐藏HTML内容 [英] Hide HTML content if a user is logged in

查看:134
本文介绍了如果用户登录,则隐藏HTML内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Go上写了一个web服务器,并问自己,有条件地隐藏HTML页面的一部分的传统方式是什么。
如果我只想显示登录按钮,当用户未登录时,我将如何实现这样的目标?
是否使用模板引擎或其他方式实现?



感谢您花时间阅读并回答此问题:)



这里

是一个工作例子:

pre $ $ $ $ $ $ $ $
$ import
html / (/,helloHandler)
http.ListenAndServe (:8000,无)
}

类型用户结构{
名称字符串
}

func helloHandler(w http。 ResponseWriter,r * http.Request){
t:= template.New(记录的示例)
t,_ = t.Parse(`
< html>
<头>
< title>登入测试< / title>
< / head>
< body>

{{if .Logged}}
这是我{{.User.Name}}
{{else}}
- 菜单 -
{{end}}


< / body>
< / html>
$)

//将登录逻辑放入中间件中
p:= struct {
记录的bool
用户*用户
} {
记录:true,
用户:&用户{姓名:Mario},
}

t.Execute(w,p)
}

要管理连接,您可以使用 http://www.gorillatoolkit.org/pkg/sessions https://github.com/codegangsta/negroni ,并在中间件内创建连接逻辑。


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.

这篇关于如果用户登录,则隐藏HTML内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆