你可以通过中间件或会话变量来设置模板变量。

huangapple go评论81阅读模式
英文:

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

问题

我好的,下面是翻译好的内容:

我很好奇如何从我的中间件中设置一个模板变量,这是我的中间件代码:

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
        }

        // 执行一些条件语句并设置为True/False
        // 设置会话变量
        session.Values["isLoggedIn"] = true

        // 保存会话
        session.Save(r, w)

        // 设置模板变量
        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>

    {{/* 在这里设置一个变量来表示您是否已登录 */}}
    {{/* 获取会话变量并相应地设置 */}}

    {{ template "body" .}}


  </body>

</html>


{{ end }}

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

英文:

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(&quot;Checking if user is logged in&quot;)

                session, err := store.Get(r, &quot;loggedIn&quot;)
                if err != nil {
                        http.Error(w, err.Error(), 500)
                        return
                }

                // Perform some If Statements and set True/False
                // Set Session Variables
                session.Values[&quot;isLoggedIn&quot;] = true

                // Save Session
                session.Save(r, w)

                // Set Template Variable
                router.ServeHTTP(w, r)
        })
}

Then in my template for my main layout:

{{ define &quot;layout&quot; }}

&lt;!DOCTYPE html&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;meta charset=&quot;UTF-8&quot;&gt;
    &lt;meta name=&quot;description&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;keywords&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;author&quot; content=&quot;&quot;&gt;
    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css&quot;&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/main.css&quot;&gt;
    &lt;title&gt; {{ .Title }} &lt;/title&gt;

  &lt;/head&gt;
  &lt;body&gt;

    {{ SET SOMETHING HERE TO SAY YOU&#39;RE LOGGED IN }}
    {{ GET THE SESSION VARIABLE AND SET ACCORDINGLY }}

    {{ template &quot;body&quot; .}}

    
  &lt;/body&gt;

&lt;/html&gt;


{{ end }}

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

答案1

得分: 2

我为个人网站做的事情是在模板中添加一个名为Session的辅助函数,并在这个函数中获取当前请求的会话,然后检查并返回请求的键。

类似这样的代码:

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

你可以在这里查看完整版本:app/render.go

英文:

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{
		&quot;Session&quot;: func(name string) interface{} {
			return sessions.GetSession(r).Get(name)
		},
	}).ParseFiles(...)
}

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

huangapple
  • 本文由 发表于 2015年8月13日 14:21:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/31980860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定