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.
<h1>Hello, <%= @user_name %>!</h1>
<ul>
<% @favorite_colors.each do |color| %>
<li><%= color %></li>
<% end %>
</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.