To test the issue, I've created a new phoenix project (v1.2.1), and simply did this:
defmodule Playground.PageController do
use Playground.Web, :controller
def index(conn, _params) do
conn
|> assign(:test, "test works")
|> put_flash(:info, "information")
|> redirect(to: "/sub")
end
def sub(conn, _) do
conn
|> render("index.html")
end
end
Once I request :index through "/", I get redirected to :sub through "/sub". For some reason, within the eex template, the flash added before the redirect is available, but the assign is not. I've looked at the Plug and Phoenix code, and can't really understand why?
I've looked at the Plug and Phoenix code, and can't really understand why?
"flash" values in Phoenix are actually stored using Plug's put_session, just before the response is sent and the response is an HTTP redirect. If it's not, the current flash value is deleted:
def fetch_flash(conn, _opts \\ []) do
flash = get_session(conn, "phoenix_flash") || %{}
conn = persist_flash(conn, flash)
register_before_send conn, fn conn ->
flash = conn.private.phoenix_flash
cond do
map_size(flash) == 0 ->
conn
conn.status in 300..308 ->
put_session(conn, "phoenix_flash", flash)
true ->
delete_session(conn, "phoenix_flash")
end
end
end
Source
Assigns on the other hand are stored directly in the conn struct and are only available for the current request/response. If you want to store something and access it in the next request, you can use Plug.Conn.put_session/3. Something like this:
def index(conn, _params) do
conn
|> put_session(:test, "test works")
|> put_flash(:info, "information")
|> redirect(to: "/sub")
end
def sub(conn, _) do
test = get_session(conn, :test)
conn
|> assign(:test, test)
|> render("index.html")
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With