如何从中间件或会话变量设置模板变量?

时间:2015-08-13 06:21:43

标签: go

我很好奇我将如何从我拥有的中间件设置模板变量,这是我的中间件:

func IsUserLoggedIn(router http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                log.Println("Checking if user is logged in")

                session, err := store.Get(r, "loggedIn")
                if err != nil {
                        http.Error(w, err.Error(), 500)
                        return
                }

                // Perform some If Statements and set True/False
                // Set Session Variables
                session.Values["isLoggedIn"] = true

                // Save Session
                session.Save(r, w)

                // Set Template Variable
                router.ServeHTTP(w, r)
        })
}

然后在我的主要布局模板中:

{{ define "layout" }}

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="author" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="/static/css/main.css">
    <title> {{ .Title }} </title>

  </head>
  <body>

    {{ SET SOMETHING HERE TO SAY YOU'RE LOGGED IN }}
    {{ GET THE SESSION VARIABLE AND SET ACCORDINGLY }}

    {{ template "body" .}}


  </body>

</html>


{{ end }}

基本上我如何在模板中访问会话变量?

1 个答案:

答案 0 :(得分:1)

我为我的个人网站做的事情是在我的模板中添加一个Session帮助程序,并在此帮助程序中检索当前请求的会话,然后检查并返回所请求的密钥。

类似的东西:

func render(w http.ResponseWriter, r *http.Request, name string, data interface{}) {
    t, err := template.New(name).Funcs(template.FuncMap{
        "Session": func(name string) interface{} {
            return sessions.GetSession(r).Get(name)
        },
    }).ParseFiles(...)
}

您可以在此处查看完整版:app/render.go