ERB vs. Phlex: Choosing the Right View Strategy for Your Rails App

The Ruby on Rails community is currently at a crossroads regarding the “View” layer. On one side, we have ERB (Embedded Ruby), the battle-tested veteran that has powered Rails since day one. On the other, Phlex has emerged as a disruptive alternative that treats HTML as pure Ruby code.

Both approaches are valid, but they favor different mental models and workflows. Here is a breakdown of the pros and cons of each to help you decide which fits your project best.

1. ERB (Embedded Ruby)

ERB is a template-based system. It feels like writing an HTML document that has “holes” where Ruby code can be injected.

The Pros

The Cons

2. Phlex

Phlex is a component-based system. It feels like writing a Ruby class that happens to output HTML.

The Pros

The Cons

The Side-by-Side: User Card Component

To see the difference in “feeling,” consider this comparison:

ERB Implementation

1
2
3
4
5
6
7
<div class="user-card">
  <%= image_tag @user.avatar %>
  <h2><%= @user.name %></h2>
  <% if @user.admin? %>
    <span class="badge">Admin</span>
  <% end %>
</div>

Phlex Implementation

1
2
3
4
5
6
7
def view_template
  div(class: "user-card") do
    image_tag(@user.avatar)
    h2 { @user.name }
    span(class: "badge") { "Admin" } if @user.admin?
  end
end

Which One Should You Choose?

Choose ERB if:

Choose Phlex if: