重定向后Flash会保留,但常规分配不会

时间:2016-09-26 16:02:59

标签: elixir phoenix-framework

为了测试这个问题,我创建了一个新的凤凰项目(v1.2.1),并且只是这样做了:

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

一旦我通过:index请求"/",我就会被重定向到:sub"/sub"。出于某种原因,在eex模板中,在重定向可用之前添加了闪存,但分配不是。我看过Plug and Phoenix代码,真的不明白为什么?

1 个答案:

答案 0 :(得分:2)

  

我看过Plug and Phoenix代码,并不能理解为什么?

"闪速"凤凰城中的值实际上是使用Plug put_session存储的,就在响应发送之前,响应是HTTP重定向。如果不是,则删除当前的闪存值:

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

另一方面,分配直接存储在conn结构中,仅适用于当前请求/响应。如果您想存储内容并在下一个请求中访问它,可以使用Plug.Conn.put_session/3。像这样:

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