Embedded Ruby (ERB) 101: Ein Einsteigerhandbuch für dynamische Vorlagen in Ruby

März 17, 2025

Have you ever wondered how Ruby developers seamlessly blend dynamic logic into their HTML templates? Enter Embedded Ruby (ERB), a powerful templating engine that allows you to embed Ruby code directly into HTML, enabling the creation of dynamic and data-driven web pages. Whether you’re building a simple blog or a complex web application, ERB is a must-know tool for Ruby developers.

In this guide, we’ll walk you through the basics of ERB, from its syntax and setup to practical examples and best practices. By the end, you’ll have a solid understanding of how to use ERB to create dynamic and maintainable templates in your Ruby projects. Let’s dive in!

What is Embedded Ruby (ERB)?

Embedded Ruby, or ERB, is a templating system that allows you to write Ruby code directly within HTML files. This combination makes it possible to generate dynamic content, such as displaying user-specific data or iterating over a list of items. ERB files typically have the .erb extension and are processed by the Ruby interpreter to produce the final HTML output.

ERB is widely used in Ruby on Rails, where it serves as the default templating engine for rendering views. However, it’s not limited to Rails—ERB can be used in any Ruby project to create dynamic templates.

How Does ERB Work?

ERB uses special delimiters to distinguish Ruby code from HTML. Here’s a quick breakdown of the key syntax:

<% %>: Executes Ruby code without outputting anything.

Beispiel: erb

<% if user_signed_in? %>
<p>Welcome back!</p>
<% end %>

<%= %>: Executes Ruby code and embeds the result into the template.
Beispiel: erb

<h1>Hello, <%= @user.name %>!</h1>

<%# %>: Adds comments that are ignored during rendering.
Beispiel: erb

<%# This is a comment and won't appear in the output %>

These delimiters allow you to mix Ruby logic with HTML, making your templates dynamic and flexible.

Setting Up ERB in a Ruby Project

Using ERB in a standalone Ruby script is straightforward. Here’s how you can get started:

Require the erb library:
Rubin

require 'erb'

Create an ERB template:
erb

<!-- template.erb -->
<h1>Welcome, <%= @name %>!</h1>

Bind data to the template and render it:
Rubin

@name = "Alice"
template = ERB.new(File.read('template.erb'))
output = template.result(binding)
puts output

In Ruby on Rails, ERB is integrated by default, so you can start using it right away in your views.

Key Features of ERB

ERB comes with several features that make it a powerful templating engine:

  • Partials: Reusable templates that can be included in other views.
    Example: erb
    <%= render 'shared/header' %>
  • Layouts: Shared structures (e.g., headers, footers) that wrap around your views.
    Example: erb
    <%= yield %> <!-- Inserts the view content here -->
  • Helpers: Ruby methods that simplify complex logic in templates.
    Example: ruby
    def format_date(date)
    date.strftime("%B %d, %Y")
    Ende
  • Escaping HTML: Prevents XSS attacks by sanitizing user input.
    Example: erb
    <%= h(user_input) %>

These features make ERB versatile and suitable for a wide range of use cases.

Common Use Cases for ERB

ERB is commonly used in scenarios like:

  • Dynamic Web Pages: Generating HTML content based on user input or database queries.
  • Email Templates: Creating customizable email layouts with dynamic data.
  • Configuration Files: Building configuration files or reports with embedded Ruby logic.

For example, you might use ERB to generate a list of products in an e-commerce application: erb

<ul>
<% @products.each do |product| %>
<li><%= product.name %> - $<%= product.price %></li>
<% end %>
</ul>

Tips for Writing Clean ERB Templates

To keep your ERB templates maintainable and efficient, follow these best practices:

  • Minimize Ruby Logic in Templates: Move complex logic into helpers or controllers.
  • Use Partials: Break down large templates into smaller, reusable components.
  • Avoid Deep Nesting: Keep conditionals and loops simple to improve readability.
  • Escape User Input: Always sanitize user input to prevent security vulnerabilities.

For example, instead of writing: erb

<% if @user.admin? %>
<p>Admin-Dashboard</p>
<% else %>
<p>User Dashboard</p>
<% end %>

You could move the logic to a helper: ruby

def dashboard_message(user)
user.admin? ? "Admin Dashboard" : "User Dashboard"
Ende

And simplify the template: erb

<p><%= dashboard_message(@user) %></p>

Example: Building a Simple ERB Template

Let’s walk through a practical example of creating and rendering an ERB template:

Define a Ruby script with data: ruby

require 'erb'
@items = ['Apple', 'Banana', 'Cherry']

Create an ERB template: erb

<ul>
<% @items.each do |item| %>
<li><%= item %></li>
<% end %>
</ul>

Render the template: ruby

template = ERB.new(File.read('template.erb'))
puts template.result(binding)

The output will be: html

<ul>
<li>Apple</li>
<li>Banana</li>
<li>Cherry</li>
</ul>

ERB vs. Other Templating Engines

While ERB is simple and beginner-friendly, other templating engines like Haml, Slim, and Liquid offer different advantages:

  • Haml: Uses indentation-based syntax for cleaner, more concise templates.
  • Slim: Similar to Haml but with a focus on minimalism and performance.
  • Liquid: Designed for safe, sandboxed templating (e.g., in Shopify).

ERB’s strength lies in its simplicity and seamless integration with Ruby, making it an excellent choice for beginners and Rails developers.

Abschluss

Embedded Ruby (ERB) is a powerful yet straightforward tool that bridges the gap between Ruby logic and HTML, making it an essential part of the Ruby ecosystem. Whether you’re building dynamic web pages, crafting email templates, or generating configuration files, ERB provides the flexibility and simplicity needed to bring your ideas to life.

As you dive deeper into Ruby development, mastering ERB will empower you to create more dynamic, maintainable, and scalable applications. So, why not start experimenting with ERB today? Build a small project, tweak some templates, and see how ERB can transform your workflow.

de_DEGerman