Skip to the workspace
Pebellslearn by building
Action View  ›  Lesson

ERB Templates and Rendering Views

ERB Templates 12 minERB mixes Ruby into HTML: <%= %> prints an escaped value, <% %> runs code without printing, and Rails renders the template named after the action unless told otherwise.

ruby on rails / ERB Templates and Rendering Views

Explore each scene at your own pace.

01 · The rule

The rule

ERB Templates and Rendering Views

The controller has found the books. Now they must become HTML. Rails views are mostly plain HTML with small windows where Ruby runs, written in a format called ERB (Embedded Ruby). Two tags do nearly all the work, and the difference between them is a single =.

The rule

<%= %> prints, <% %> only runs — and printing is escaped.

<%# app/views/books/index.html.erb %>
<h1>Books (<%= @books.size %>)</h1>

<% if @books.empty? %>
  <p>No books yet.</p>
<% else %>
  <ul>
    <% @books.each do |book| %>
      <li><%= book.title %> by <%= book.author %></li>
    <% end %>
  </ul>
<% end %>
  • <%= expression %> — runs Ruby and inserts the result into the page.
  • <% code %> — runs Ruby and prints nothing: loops, if, end.
  • <%# comment %> — ignored.

Everything printed with <%= %> is HTML-escaped: < becomes &lt;. If a member's review contains a <script> tag, the page shows the text instead of running it. This protects you from cross-site scripting. raw and .html_safe switch escaping off; reserve them for HTML your own code produced.

Rendering: the file name tells Rails what it is. index.html.erb is the index action's template, HTML format, ERB handler. By default BooksController#index renders app/views/books/index.html.erb. From an action you can choose another:

render :edit                       # books/edit.html.erb
render "shared/empty"              # another folder
render plain: "OK"                 # just text
render json: @book                 # JSON

Keep logic out of templates. A view that calls Book.where(...) is doing the controller's job; a view doing sums is doing the model's.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.