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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)