How Phoenix View works exactly?

I am bit confused , how exactly phoenix view works to render templates.Lets say i controller like follow

defmodule XXXX.DepartmentController do
   def new(conn, _params) do
    render conn, "new.html", changeset: changeset

after it invokes render/3 , how it works?

render/3 is a function provided by Phoenix.Controller that gets imported when you do use MyApp.Web, :controller.

What it does is this: It tries to automatically determine the name of the corresponding view module (i. e. if your controller is called MyApp.MyController, it will look for MyApp.MyView) and then calls Phoenix.View.render/3 on that.

Note that Phoenix.View.render/3 is different from Phoenix.Controller.render/3
The docs explain this nicely:

It is also important to not confuse Phoenix.Controller.render/3 with Phoenix.View.render/3 in the long term. The former expects a connection and relies on content negotiation while the latter is connection-agnostic and typically invoked from your views.

If you don’t want Phoenix.Controller.render/3 to infer the view module name automatically, you can also use Phoenix.Controller.put_view/2 (see docs) in order to set it manually.

If you want to learn more, you can also take a look at the guides provided for Controllers and Views.

Thanks man, but the template name which we given in render/3 is rendered by layout/app.html.eex, So is it Invoke layout view before particular controller view

By default, Phoenix will render your views inside a layout. You can change the layout or disable this with Phoenix.Controller.put_layout/3.

This means, it will take the output of your view and render it within the layout.
However, the layout is not where you are supposed to put your view logic, this should be done with actual Views that in turn will have their own eex files.

You can read more about this behavior in the docs of Phoenix.Controller and there is a really nice explanation of how everything works together in the Phoenix Guide on Views.

I think it’s worthwhile also noting that Phoenix compiles your template files as render/3 functions in to your view modules.

This is why View modules are always required even though they mostly appear empty. It’s also why template rendering is so fast, there’s negligible processing to be done at runtime.

1 Like

Neither View nor Controller modules are required, both are simply Plug modules. Phoenix merely offers convenience functions around that :slight_smile:

View’s are required by Controller’s.

Only if you call render or so. You can call text or json or so as well, render is what requires the view, not the controller. :slight_smile:

1 Like

Yup, both of my answers were addressing the original question.

I am bit confused , how exactly phoenix view works to render templates