Ruby ERB Templates
Take your programming skills to the next level with interactive lessons and real-world projects.
Explore Coddy →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.
What are ERB Templates?
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.
Basic Syntax
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)
Example Usage
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
Common Use Cases
ERB templates are frequently used in various scenarios:
- Generating HTML pages in web applications
- Creating email templates
- Producing configuration files
- Generating reports or documents
Best Practices
- Keep logic in templates minimal. Complex operations should be handled in Ruby classes or helpers.
- Use
<%= %>for outputting values and<% %>for control structures. - Escape user input to prevent XSS attacks. In Rails, use
<%= h(user_input) %>or<%= user_input.html_safe %>when appropriate. - Consider using partials for reusable template components.
- Leverage Ruby String Interpolation within ERB for cleaner code.
Advanced Features
ERB offers advanced features for more complex templating needs:
- Trim mode: Control whitespace output with
ERB.new(template, trim_mode: '-') - Safe level: Set execution restrictions for untrusted templates
- Custom delimiters: Change the default
<%and%>tags
Integration with Ruby Frameworks
ERB is tightly integrated with Ruby web frameworks:
- In Ruby on Rails, ERB is the default templating engine for views.
- Sinatra supports ERB out of the box for rendering templates.
- Many other Ruby frameworks and libraries use ERB for templating needs.
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.
Related Concepts
To deepen your understanding of Ruby and web development, explore these related topics:
- Ruby Modules for organizing code
- Ruby Blocks for creating reusable code snippets
- Ruby and HTTP for web communication