dongluo3962 2018-08-24 16:17
浏览 45

处理程序中的变量未传递给模板

Learning Go and Gin from here. So I have a router like this

userRoutes.POST("/login", ensureNotLoggedIn(), performLogin)

and the handler function is like this

func performLogin(c *gin.Context) {
  username := c.PostForm("username")
  password := c.PostForm("password")
  if isUserValid(username, password) {
    token := generateSessionToken()
    c.SetCookie("token", token, 3600, "", "", false, true)
    //is_logged_in is not working in template
    c.Set("is_logged_in", true)
    render(c, gin.H{"title": "Successful Login"}, "login-successful.html")
  } else {
    c.HTML(http.StatusBadRequest, "login.html", gin.H{
        "ErrorTitle":   "Login Failed",
        "ErrorMessage": "Invalid credentials provided",
    })
  }
}

and my template is like

{{ if .is_logged_in }}
      <li><a href="/article/create">Create Article</a></li>
{{ end }}
{{ if not .is_logged_in }}
    <li><a href="/u/register">Register</a></li>
{{end}}

But in the end this variable in template seems not working, only the second section shows, the first link 'Create Article' is always hiding.

Update

I changed the handler function to something like this,

        render(c, gin.H{"title": "Successful Login", "is_logged_in": c.MustGet("is_logged_in").(bool)}, "login-successful.html")

explicitly passing the variable. Now the template element hide and show is correct. So was there anything changed in Golang or Gin to make .Set() behaving differently?

  • 写回答

1条回答 默认 最新

  • dougaodi8895 2019-01-19 07:14
    关注

    Do you load the template firstly?

    func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Main website",
        })
    })
    router.Run(":8080")
    

    } templates/index.tmpl

    <html>
    <h1>
        {{ .title }}
    </h1>
    

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看