0
0
RailsConceptBeginner · 3 min read

What is ERB in Rails: Explanation and Usage

ERB in Rails stands for Embedded Ruby, a templating system that lets you write Ruby code inside HTML files. It processes these files to produce dynamic HTML pages by mixing Ruby logic with static content.
⚙️

How It Works

ERB works like a translator between Ruby code and HTML. Imagine you have a recipe book where some steps depend on the ingredients you have. ERB lets you write those steps with conditions and loops inside your HTML, so the final recipe changes based on what you provide.

When Rails renders a view, ERB reads the template file and runs the Ruby code inside special tags. It then replaces those tags with the Ruby code's output, creating a complete HTML page that the browser can show.

💻

Example

This example shows an ERB template that greets a user by name and lists their favorite colors.

erb
<h1>Hello, <%= @user_name %>!</h1>
<ul>
  <% @favorite_colors.each do |color| %>
    <li><%= color %></li>
  <% end %>
</ul>
Output
<h1>Hello, Alice!</h1> <ul> <li>Red</li> <li>Blue</li> <li>Green</li> </ul>
🎯

When to Use

Use ERB in Rails whenever you want to create dynamic HTML pages that change based on data or user input. It is perfect for views where you need to show lists, conditionally display content, or insert values from your Ruby code.

For example, ERB is used to build user profiles, product pages, or dashboards that update with real-time information.

Key Points

  • ERB lets you embed Ruby code inside HTML using special tags like <% %> and <%= %>.
  • It runs Ruby code and inserts the result into the HTML output.
  • ERB templates are the default way to create views in Rails.
  • Helps make web pages dynamic and data-driven.

Key Takeaways

ERB is a templating system that mixes Ruby code with HTML to create dynamic web pages.
Use ERB tags to run Ruby code and insert its output into HTML templates.
ERB is the default view template engine in Rails for rendering HTML.
It helps build pages that change based on data or user actions.