0
0
RailsHow-ToBeginner · 4 min read

How to Use ERB Syntax in Rails: Simple Guide

In Rails, use ERB syntax to embed Ruby code inside HTML files by placing Ruby code within <% %> tags. Use <%= %> to output Ruby expressions directly into the HTML, and <% %> for Ruby code that runs without output.
📐

Syntax

ERB syntax lets you mix Ruby code with HTML. Use <% code %> to run Ruby code without showing output. Use <%= expression %> to run Ruby code and insert its result into the HTML.

Example parts:

  • <% %>: Executes Ruby code but does not print anything.
  • <%= %>: Executes Ruby code and inserts the result into the HTML.
  • <%# %>: Comments out ERB code, ignored in output.
erb
<h1>Welcome</h1>
<p>Current time: <%= Time.now %></p>
<% if user_signed_in? %>
  <p>Hello, <%= current_user.name %>!</p>
<% else %>
  <p>Please sign in.</p>
<% end %>
💻

Example

This example shows a simple ERB template that displays a greeting based on whether a user is signed in.

erb
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ERB Example</title>
</head>
<body>
  <h1>Welcome to Our Site</h1>
  <p>Current time: <%= Time.now.strftime('%H:%M:%S') %></p>
  <% if @user_signed_in %>
    <p>Hello, <%= @user_name %>!</p>
  <% else %>
    <p>Please sign in to continue.</p>
  <% end %>
</body>
</html>
Output
<h1>Welcome to Our Site</h1> <p>Current time: 14:30:45</p> <p>Hello, Alice!</p>
⚠️

Common Pitfalls

Common mistakes include:

  • Using <%= %> when you don't want output, which can cause unwanted text.
  • Forgetting to close ERB tags, causing syntax errors.
  • Trying to use Ruby code outside ERB tags.
  • Not escaping HTML when outputting user data, risking security issues.
erb
<!-- Wrong: outputs Ruby code instead of running it -->
<p><% if user_signed_in? %>Welcome!<% end %></p>

<!-- Right: use control flow outside output tags -->
<% if user_signed_in? %>
  <p>Welcome!</p>
<% end %>
📊

Quick Reference

ERB TagPurposeExample
<% code %>Run Ruby code without output<% if logged_in? %>
<%= expression %>Run Ruby code and output result<%= user.name %>
<%# comment %>ERB comment, ignored<%# This is a comment %>

Key Takeaways

Use <%= %> to insert Ruby output into HTML.
Use <% %> for Ruby code that runs but does not output.
Always close ERB tags properly to avoid errors.
Escape user data when outputting to prevent security risks.
ERB lets you create dynamic HTML pages by mixing Ruby and HTML.