Rails' before_filter equivalent in Phoenix

前端 未结 2 1996
轮回少年
轮回少年 2021-01-04 03:30

I\'ve just started working on my first Phoenix app, and the issue is that I have some common lines of code in every action in my controller, that I would like to separate ou

2条回答
  •  抹茶落季
    2021-01-04 03:57

    You can indeed achieve this with a Plug and Plug.Conn.assign.

    defmodule TestApp.PageController do
      use TestApp.Web, :controller
    
      plug :store_something
      # This line is only needed in old phoenix, if your controller doesn't
      # have it already, don't add it.
      plug :action
    
      def index(conn, _params) do
        IO.inspect(conn.assigns[:something]) # => :some_data
        render conn, "index.html"
      end
    
      defp store_something(conn, _params) do
        assign(conn, :something, :some_data)
      end
    end
    

    Remember to add the plug declaration before your action plug, as they are executed in-order.

提交回复
热议问题