使用插件分配来查看(长生不老药/凤凰)

Use assign from plug to view (elixir / phoenix)

我有我的 api 管道,我想在其中添加一个插件,它基本上在数据库中执行一些操作,并根据响应进行分配,然后我在视图中使用它。

我在将分配从插件传递到视图时遇到问题。

web/router.ex

pipeline :api do
  plug ApiV2.Plug.Authenticate, repo: Auth.Repo
  plug :accepts, ["json"]
end

web/controllers/auth.ex(只是赋值)

defmodule ApiV2.Plug.Authenticate do
     @behaviour Plug
     import Plug.Conn
     import Phoenix.Controller

  def init(opts), do: opts

  def call(conn, _opts) do
    assign(conn, :current_user, 'user')
  end

end

web/controllers/address_controller.ex

defmodule ApiV2.AddressController do
  use ApiV2.Web, :controller

  alias ApiV2.Address

  def index(conn, params) do
    json conn, @current_user
  end
end

我已经到了它试图 return :current_user (我想)的地步,但是,由于分配错误,它只 returns

null

我错过了什么?

谢谢

使用 assign 设置的值在 conn.assigns 地图中可用。 @current_user 是 returns nil 的模块属性,因为它未在此模块中设置。

这应该有效:

json conn, conn.assigns.current_user