Data transformation in controllers instead of views?

Hi everyone,

I’m relatively early in my journey as a developer, and am teaching myself Phoenix.

I have read through the “Programing Phoenix > 1.4” book, am working through the Phoenix docs (and have also searched the web on this question), but I’m not quite clear where to draw the boundary between controllers and views.

Some sources suggest doing data transformation in views (as opposed to controllers), but it seems simpler to me to do anything data related in the controller, and basically leave the auto-generated view code alone.

What do you think about this mental shortcut of basically ignoring the view for now and thinking only in controllers and templates for this part of the code?

Thank you!

I am doing both. Actually, I am more and more moving towards defining the JSON response structure in the view. It feels more like the Phoenix way and I think in the long term, it helps understanding the response structure.

You are also more flexible with your data layer. If something changes, you don’t need to change the API response. You can just rewire the defined reponse structure to the new data structure. Of course, this can also be done in the controller but there is the risk of bloating the controller. The view seems to be a more appropriate place for that.

This doesn’t mean you have to do this. I started with the controller and whenever I see something might be more useful to define in the view, I gonna change that.

1 Like

I handle it like that: The data send by the controller should be the minimal data needed to send a response no matter what type is may be. The view should then transform the data into the specific response (html, json, …).


Very helpful, thank you both, I will bring the view back into my thinking about what goes where in Phoenix.