陶醉的闪光消息不显示

I have created a revel web application with default skelton.

I have created a new route/action/view:

Controller action:

func (c Ctrl1) Action3() revel.Result {
    variable1 := "test1"
    variable2 := "test2"
    c.Flash.Error("Message")
    return c.Render(variable1,variable2)
}

Action3.html:

{{set . "title" "Test"}}
{{template "header.html" .}}
{{template "flash.html" .}}
Hello: {{.variable1}}
{{template "footer.html" .}}

The first time i have runned my webapp, i saw the flash message. But next times, if i refresh the page, it disapears !

I have restarted revel

Thanks

I'm not familiar with revel, but message "flashing" is typically used when you need some user communication to carry over through a redirect. The godoc seems to describe it as exactly for that use case as well.

If you're rendering a template directly in this request handler, you probably shouldn't be using c.Flash. My guess of what is happening is that revel will only show the flash message received with the request. Calling c.Flash.Error sets the field in the cookie, which means it will be sent back to the caller, not to the template. On the next render, it will read from the cookie that the caller sends back to the server, which would include this flash message. Apparently, though, setting a new flash message replaces the old one, causing it to (yet again) send it to the caller not the template.

The good news is that there's really only one way for your message to get on the page, and you can almost definitely shoehorn your message there: the template data! Instead of calling c.Flash.Error, send the message using the usual mechanisms. In this case, assuming your flash.html template contains something like:

{{ if .flash.error }}
    <div class="error">{{ .flash.error }}</div>
{{ end }}

you should be able to pass that data by replacing the c.Flash.Error("Message") line with:

c.ViewArgs["flash"] = map[string]string{"error": "Message"}

This seems to be a known issue/expected behaviour. As the discussion on github seems to suggest, to use the flash message for errors, you either need to redirect:

c.Flash.Error("Message")
return c.Redirect("App/ShowError")

Or using the field template function if you need to add the error message next to a specific input element.

Seeing as you're not rendering a form in your template, I'm guessing a redirect is what you need to add.


Incidentally: revel is, by many, considered harmful. I'd urge you to not use a framework that attempts to force you to use go following a classical MVC structure. Nowadays, most web applications are single page apps using react on the client side, and an API based backend. It might make your life easier to go down this route, too?