Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 37 ยท Views and Templates

ERB Templates in Rails

Learn how Rails views use ERB: the three main tags, loops and conditionals, automatic HTML escaping, how controller instance variables reach templates, and the file naming rules. Runnable ERB examples included.

The view layer turns data into the HTML a browser displays. In Rails the default template language is ERB (Embedded Ruby): plain HTML with small pieces of Ruby inside special tags. It is not a new language. The erb library ships with Ruby itself, which means we can run real ERB in the examples of this lesson. For ERB outside of Rails see ERB in Ruby.

You will learn the ERB tags, how loops and conditions look in a template, how data flows from a controller to a view, why Rails escapes output automatically (and how to avoid XSS mistakes), and how template files are named and found.

Where views live

For ArticlesController#show, Rails looks for app/views/articles/show.html.erb. The name has three parts: the action (show), the format (html) and the handler (erb). A JSON view would be show.json.jbuilder, a plain text one show.text.erb.

TEXT
app/views/
  layouts/
    application.html.erb     <- the page frame around every view
  articles/
    index.html.erb
    show.html.erb
    _article.html.erb        <- a partial (starts with an underscore)
    _form.html.erb

The ERB tags

Tag Meaning
<% ruby %> Run Ruby, print nothing
<%= ruby %> Run Ruby and print the result (HTML-escaped)
<%# comment %> A comment, not sent to the browser
<%- ... -%> / -%> Trim surrounding whitespace
<%== ruby %> Print without escaping (dangerous)

Here is a real template. It is read-only on this page because it relies on Rails helpers like link_to:

ERB
<%# app/views/articles/index.html.erb  (read-only) %>
<h1>Articles</h1>

<% if @articles.empty? %>
  <p>Nothing here yet.</p>
<% else %>
  <ul>
    <% @articles.each do |article| %>
      <li><%= link_to article.title, article %></li>
    <% end %>
  </ul>
<% end %>

Each Ruby block needs its own <% end %>. The pattern <% ... do %> ... <% end %> is how you write loops.

Running real ERB

Plain ERB works without Rails. This example fills a template with a few objects, just as a controller hands @articles to a view.

Ruby ERB with a loop and a condition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

result(binding) evaluates the template in the current scope, so it can see the local variable articles. Rails does something similar: it evaluates the template inside an object that has all your controller's instance variables copied into it.

How controller data reaches the view

Ruby
# read-only
class ArticlesController < ApplicationController
  def show
    @article = Article.find(params[:id])     # set in the controller
    @related = @article.related.limit(3)
  end
end
ERB
<%# read-only: show.html.erb %>
<h1><%= @article.title %></h1>
<p><%= @article.body %></p>

Before rendering, Rails copies every instance variable of the controller into a view object. That is why @article works in the template. Local variables of the action are not copied.

Stand-in: copying instance variables into a view

This demonstrates the trick with a controller object and instance_variable_set.

Ruby Stand-in: assigns from controller to view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice local_only never appears. This is exactly the rule: only @variables travel to the view.

Automatic HTML escaping

Suppose a visitor saves their name as <script>alert(1)</script>. If the page printed it raw, the script would run in other users' browsers. That attack is cross-site scripting (XSS). Rails stops it by escaping <%= %> output by default: < becomes &lt;.

ERB
<%# read-only %>
<p>Hello, <%= @user.name %></p>
<%# if name is "<b>Kay</b>" the browser shows the literal text <b>Kay</b> %>

You must say explicitly when HTML is meant to be output:

ERB
<%# read-only %>
<%= raw @article.body %>          <%# dangerous: no escaping %>
<%= @article.body.html_safe %>    <%# dangerous, same thing %>
<%= sanitize @article.body %>     <%# safe: removes scripts, keeps b, i, a, p ... %>

Prefer sanitize (or a Markdown renderer with sanitizing) for user-provided HTML.

Ruby Escaping stops XSS

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

html_safe and raw do not make text safe. They only tell Rails "I promise this is already safe". Using them on user input is the most common cause of XSS in Rails apps. Check the secure Ruby code lesson for the wider picture.

Keep logic out of templates

Templates should mostly display. A few conditions and loops are fine, but business rules belong in models, and formatting belongs in helpers (next lessons). Compare:

ERB
<%# read-only: too much logic %>
<% if @order.items.sum { |i| i.price * i.qty } > 100 && @user.created_at < 1.year.ago %>
  <p>Free shipping!</p>
<% end %>

<%# better: a named method on the model %>
<% if @order.free_shipping? %>
  <p>Free shipping!</p>
<% end %>

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the difference between <% %> and <%= %>?

    The equals sign means 'output the value of this expression'.
  2. 2. How does @article set in a controller action become available in the view?

    Instance variables are copied across; local variables are not.
  3. 3. What does Rails do to the output of <%= @comment.body %> by default?

    Automatic escaping protects against cross-site scripting.
  4. 4. Which is the safest way to show user-provided HTML with basic formatting?

    sanitize keeps a whitelist of tags and removes scripts. raw and html_safe skip protection.

Summary

  • Rails views are ERB files named action.format.handler, such as show.html.erb.
  • <% %> runs Ruby, <%= %> prints (escaped), <%# %> is a comment.
  • Controller instance variables are copied into the view; local variables are not.
  • Output is HTML-escaped automatically; raw and html_safe switch protection off.
  • Keep rules out of templates; use model methods and helpers.

Next: Layouts and Partials