猿问

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

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


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 }}

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


RISEBY
浏览 164回答 1
1回答
随时随地看视频慕课网APP

相关分类

Go
我要回答