如何从控制器更改 Conn 中的视图模块?

How do I change the View module in Conn from a controller?

我的 CustomerEvents 控制器中有一个函数如下:

  def index(conn, params) do
    list = CustomerEvents.list_customer_events(params)

    conn |> put_view(MyApp.CustomersView)

    render(conn, "index.json", customers: list)
    end
  end

对于此特定函数,list_customer_events 的结果需要转到我的 CustomersView,而不是它默认尝试使用的 CustomerEvents 视图。

通过阅读文档,我认为 conn |> put_view(MyApp.CustomersView) 足以进行更改,但似乎没有任何区别。检查 conn 对象时,我仍然看到:

:phoenix_view => MyApp.CustomerEventViewprivate 地图中。根据我目前的理解,我希望它是 :phoenix_view => MyApp.CustomerView.

如何正确地进行这种更改?

问题是您没有正确传送 conn

conn |> put_view(MyApp.CustomersView)
render(conn, "index.json", customers: list)

elixir 中的所有函数 return 一个新值,这意味着当您使用 conn |> put_view(MyApp.CustomersView) 时,您会得到一个新的 conn,但是您发送以渲染旧值。

要呈现正确的视图,您要么通过管道传输所有内容,要么发送更新后的值:

updated_conn = conn |> put_view(MyApp.CustomersView)
render(updated_conn, "index.json", customers: list)

conn 
|> put_view(MyApp.CustomersView)
|> render("index.json", customers: list)