ERB (Embedded Ruby) is a powerful templating system in Ruby that allows you to embed Ruby code within HTML or other text documents. It's widely used for generating dynamic content in web applications, particularly with frameworks like Ruby on Rails.
ERB templates combine plain text with Ruby code snippets, enabling developers to create dynamic content easily. These templates are processed by the ERB library, which evaluates the embedded Ruby code and replaces it with the resulting output.
ERB uses special tags to embed Ruby code within a template:
<%= %>
- Evaluates Ruby code and outputs the result<% %>
- Executes Ruby code without outputting the result<%# %>
- Comments (not executed or output)Here's a simple example of an ERB template:
<!-- greeting.erb -->
<h1>Hello, <%= name %>!</h1>
<p>Today is <%= Time.now.strftime("%A, %B %d, %Y") %>.</p>
<% if logged_in? %>
<p>Welcome back!</p>
<% else %>
<p>Please log in.</p>
<% end %>
To render this template in Ruby:
require 'erb'
name = "Alice"
logged_in = true
template = File.read('greeting.erb')
renderer = ERB.new(template)
result = renderer.result(binding)
puts result
ERB templates are frequently used in various scenarios:
<%= %>
for outputting values and <% %>
for control structures.<%= h(user_input) %>
or <%= user_input.html_safe %>
when appropriate.ERB offers advanced features for more complex templating needs:
ERB.new(template, trim_mode: '-')
<%
and %>
tagsERB is tightly integrated with Ruby web frameworks:
Understanding ERB is crucial for Ruby developers, especially those working on web applications. It bridges the gap between static content and dynamic Ruby code, enabling the creation of flexible and powerful templates.
To deepen your understanding of Ruby and web development, explore these related topics: