When creating a controller in a Phoenix application, at least three files are created:

  • The controller (e.g. PageController)
  • The view (e.g. PageHTML)
  • The template (e.g. index.html.heex)

This is a great structure when you're building CRUD applications. Sometimes, especially if you have a single action, it would be nice to have a single file for the controller, view, and template.

I tweeted the idea out this morning with a quick example. After thinking about it a bit more, and with some of the feedback, I've settled on something to use going forward.

Sometimes all that ControllerHTML module plus templates just seems like overkill. Here’s a way to make a controller with inline templates (like render/1 within a LiveView) #myelixirstatus pic.twitter.com/2WhsqAw3pr β€” Andrew Timberlake (@ATimberlake) October 7, 2024

I create a sub-module within the controller named View which contains the template functions using the heex ~H sigil. Then the magic is done with put_view(conn, __MODULE__.View) in the controller (handled at the top of the controller as a plug).

continue reading on andrewtimberlake.com

⚠️ This post links to an external website. ⚠️