Sheharyar
Sheharyar

Reputation: 75740

Use custom View with multiple Controllers in Phoenix

In Phoenix, is there some way that I can specify which View to use instead of letting the Controller inflect from the namespace?

I have multiple controllers and for each controller's view the methods are same. I would like to create a single view and use it with (almost) all of my controllers.

Is this possible? And more importantly, is this a bad practice or justified in my situation?

Upvotes: 12

Views: 2246

Answers (1)

Chris McCord
Chris McCord

Reputation: 8100

You can use put_view/2 to set the view module. It is not bad practice given your description. You can put the following code inside your controller:

plug :put_view, MyApp.TheView

Or you can modify the view for a single function inside your controller, e.g.:

  def index(conn, _params) do
    conn
    |> put_view(MyApp.TheView)
    |> render("index.html")
  end

Upvotes: 19

Related Questions