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

时间:2019-12-10 12:50:46

标签: elixir phoenix

我的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.CustomerEventView地图中的

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

如何正确进行此类更改?

1 个答案:

答案 0 :(得分:2)

问题是您没有正确传送conn

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

长生不老药中的所有函数都返回一个新值,这意味着当您使用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)