Missed Opportunity: Phoenix needs a guide for creating REST APIs

That’s is because of EEx, which actually compiles templates into functions of the view module. The compiled project only has modules and no template files anymore. This makes it quite a bit faster than frameworks without precompiled templates. That’s also why json and html views actually work with the same api even if one is using written out render functions and the other is using templates. Both are called using render/2 on the view module.

You could even use the render function to e.g. prepare date for the template:

def render("show.html", %{date: date} = assigns) do
  data = %{assigns | date: Date.to_iso8601(date)}
  render_template("show.html", data)
end

So the view is hardly as useless as the mostly empty modules make it look like. It’s more due to the fact that phoenix is compiling the 95% use-cases so efficiently into the module that often times you don’t need to modify it. But if you do to you can.

You can do the same in plug/phoenix as well: json(conn, data). But it means your data must be json-encodable by globally defined rules. This get’s problematic as soon as you want to have more than one json representation based on the same data. If you want to work around that limitation just in the controller you’d put a lot of data mapping logic into the controller, while phoenix simply encourages to put all that logic into a view module right from the start (which is also where it really belong).

3 Likes