3

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?

tomriddle_1234
  • 3,145
  • 6
  • 41
  • 71
  • Just for the record, I've just learned that 'this is the way it's supposed to be'. See https://github.com/gin-gonic/gin/issues/1512#issuecomment-418021853 — citing @[isgj](https://github.com/isgj) on GitHub, _No, the template can see only what you pass to the `c.HTML(...)`. What you set with `c.Set(...)` can be seen only by the middleware and the handler._ – Gwyneth Llewelyn Jun 27 '20 at 19:28
  • Also, since this example comes from [this most wonderful tutorial](https://chenyitian.gitbooks.io/gin-tutorials/tdd/11.html) by Chen Yi-Tian, maybe, if someone has a way to contact him, it would be nice if he could update that specific page explaining how variables are passed to templates... – Gwyneth Llewelyn Jun 27 '20 at 19:54

1 Answers1

2

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>
xie cui
  • 55
  • 5