gin-contrib / sessions

Gin middleware for session management
MIT License
1.46k stars 194 forks source link

How to use flashes in a template? #33

Open mrichman opened 7 years ago

mrichman commented 7 years ago

I can't seem to find an example of how to do this. My method feels like a hack.

I've got my login handler, and I want to show errors if authentication fails. So I'm adding the error to session via AddFlash(). I understand that once the flashes are read from, they are no longer available.

func login(c *gin.Context) {

    username := c.PostForm("username")
    password := c.PostForm("password")

    u := &User{}

    if err := db.Where("username = ? AND password = ?", username, password).First(&u); err != nil {
        session := sessions.Default(c)
        session.AddFlash(err.Error)
        session.Save()
        c.HTML(http.StatusOK, "login.html", gin.H{
            "title": "Login", "session": session,  // SHOULD I HAVE TO PASS SESSION TO MY TEMPLATE?!
        })
    } else {
        session := sessions.Default(c)
        session.Set("user", u.ID)
        session.Save()
        c.HTML(http.StatusOK, "index.html", gin.H{
            "title": "Login", "user": u,
        })
    }
}

And I'm displaying the flashes thusly:

{{ range $flash := .session.Flashes }}
Flash: <li>{{ $flash }}</li>
{{ end }}

Should I have to pass the session to my template just to get at the flashes?

expatmt commented 6 years ago

Try this:

session.Set("user", u.ID)
session.AddFlash("This is a flash message.")
session.Save()
c.HTML(http.StatusOK, "index.html", gin.H{
    "title": "Login",
    "user": u,
    "flashes": session.Flashes(),
})

In the template:

{{range .flashes}}{{.}}{{end}}

Although I am unable to decipher how to get the flash keys working, so cannot help on that.

To use custom flash containers, so you can have Error, Info, Warning type messages:

session.AddFlash("Warning flash.", "Warn")
session.AddFlash("Info flash.", "Info")
session.Save()

c.HTML(http.StatusOK, "index.html", gin.H{
    "title": "Login",
    "user": u,
    "MsgInfo":    session.Flashes("Info"),
    "MsgWarn":    session.Flashes("Warn"),
})

And in the template:

{{range .MsgInfo}}{{.}}{{end}}
{{range .MsgWarn}}{{.}}{{end}}

Seems to be working so far for me.

leeyuanzhang commented 6 years ago

It always seems to exist and won't disappear after Flashes

leeyuanzhang commented 6 years ago

[solved] Save Save Save !!!

jwwb681232 commented 5 years ago

There is a problem with carrying the data load template through c.HTML. If there is an error in the submission of a form, return to the previous page, and the form will be submitted repeatedly when F5 refreshes.