Rails ERB means Embedded Ruby is a templating system that lets you embed Ruby code within HTML to create dynamic content same as JSX if you're familiar with React Js.

This is a important part of Rails development and makes building robust web applications.

In this post, I’ll walk you through the basics of ERB syntax, so you can start building Rails applications with confidence.

What is ERB in Ruby on Rails?

ERB, or Embedded Ruby, allows you to write Ruby code within an HTML document. The server processes this Ruby code and sends the generated HTML to the browser. For instance, you can display dynamic content like user names, lists of posts, or conditional sections in your web pages using ERB.

ERB Syntax Basics

Now let's learn ERB Syntax in simple words.

1. Displaying Ruby Code in Views

To embed Ruby code in your view files, use <%= %> tags. Anything inside these tags will be evaluated, and the output will appear in the HTML.

erb  
<%= "Hello, Ali" %>

Output:

html  
Hello, Ali!

2. Running Ruby Code Without Output

If you want to run Ruby code without displaying it on the page, use <% %> tags.

erb  
<% user_name = "Alice" %>

This runs the Ruby code but doesn’t produce any visible output in the HTML.

3. Using Conditionals in ERB

You can use if, else, and elsif statements to control what content is displayed.

erb  
<% if logged_in? %>  
  <p>Welcome back, <%= current_user.name %>!</p>  
<% else %>  
  <p>Please log in to continue.</p>  
<% end %>  

4. Iterating Over Collections

To display lists or data sets, you can use loops like each.

erb  
<ul>  
  <% @posts.each do |post| %>  
    <li><%= post.title %></li>  
  <% end %>  
</ul>  

Prevent the HTML Issues in ERB

By default, Rails escapes potentially harmful HTML to prevent security vulnerabilities like cross-site scripting (XSS). For example:

erb  
<%= "<script>alert('Hello');</script>" %>

The output will be:

html  
&lt;script&gt;alert('Hello');&lt;/script&gt;

If you need to output raw HTML, use the html_safe method cautiously:

erb  
<%= "<strong>Important!</strong>".html_safe %>

Couple of Resources for Learning ERB

So ERB is a powerful tool for creating dynamic web pages in Rails.

Practice these fundamental concepts, and soon, writing ERB templates will feel easy for sure.

Keep learning, let me know the feedback in the comments below. Thanks


Comments(0)