Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in handler is not passing to template

Tags:

go

go-gin

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?

like image 963
tomriddle_1234 Avatar asked Apr 07 '26 16:04

tomriddle_1234


1 Answers

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>
like image 188
xie cui Avatar answered Apr 10 '26 06:04

xie cui