Skip to content

Lesson 2 — Two approaches to Phlex in Rails

Before writing a single view, make a conscious architectural decision: full Phlex or hybrid?

Approach 1 — Full Phlex

Delete all ERB. Render Phlex views directly from controllers. The entire UI lives in app/views/ and app/components/.

1
2
3
4
5
6
7
8
# app/controllers/boards_controller.rb
class BoardsController < ApplicationController
  layout false   # disable Rails' built-in layout system

  def index
    render Views::Boards::Index.new(boards: current_user.boards)
  end
end

Best for: greenfield apps, teams comfortable with Ruby-first views, maximum consistency.

Tradeoff: steeper initial learning curve, all UI must be expressed as Ruby methods and blocks.

Approach 2 — Hybrid (ERB + Phlex components)

Keep ERB for page-level views. Use Phlex components for the complex, reusable parts. ERB renders components with the standard render helper:

<%# app/views/boards/index.html.erb %>
<h1>Your Boards</h1>

<%= render Components::EmptyState.new(message: "No boards yet") if @boards.empty? %>

<div class="board-grid">
  <% @boards.each do |board| %>
    <%= render Components::BoardCard.new(board: board) %>
  <% end %>
</div>

Best for: migrating existing Rails apps, pages with significant static HTML content, teams transitioning gradually.

Tradeoff: two template languages in the same codebase, plain "..." in Phlex views that contain prose text.

Hybrid as a migration strategy

The hybrid approach is not just a compromise — it is the recommended path for adopting Phlex in an existing app. The Phlex documentation puts it clearly:

“Start by extracting components and using them in your existing Rails views. This will help you get the most out of Phlex early on without too much effort.”

A practical migration plan:

  1. Install phlex-rails alongside existing ERB views
  2. Extract the most complex, repeated UI into Phlex components
  3. Render those components from ERB with <%= render Components::X.new(...) %>
  4. Gradually convert full pages to Phlex views as you touch them
  5. Convert layouts last — they are the most disruptive change

You can track progress in the Rails console:

1
Phlex::HTML.descendants.size   # how many Phlex components are loaded

What KanbanFlow uses

KanbanFlow is a greenfield app, so we use full Phlex throughout. All ERB is deleted from day one. This gives the clearest demonstration of what Phlex makes possible.

If you are applying these lessons to an existing app, the hybrid approach is the right choice — everything in this module applies equally, just keep your ERB views and add Phlex components alongside them.

Disabling Rails’ layout system

For full Phlex, add this to ApplicationController:

1
2
3
class ApplicationController < ActionController::Base
  layout false
end

This tells Rails not to wrap rendered views in an ERB layout. Our Phlex layout component handles the full page structure instead.