dongshijiao2363 2015-08-13 06:21
浏览 27
已采纳

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

I'm curious as to how I would set a template variable from a piece of middleware I have, this is my middleware:

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

Then in my template for my main layout:

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

Basically how can I access a session variable inside my template?

  • 写回答

1条回答 默认 最新

  • dongpu1879 2015-08-13 08:17
    关注

    The thing I did for my personal website was to add a Session helper available in my templates, and in this helper retrieve the session of the current request then check and return the requested key.

    Something like that:

    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(...)
    }
    

    You can see the full version here: app/render.go

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?