Datsik
Datsik

Reputation: 14824

How can I set template variables from my middleware or session variable?

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?

Upvotes: 2

Views: 668

Answers (1)

Elwinar
Elwinar

Reputation: 9519

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

Upvotes: 2

Related Questions