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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题