Ruby on Rails/ActionView/ERb

ERb (Embedded Ruby) is the default template language included with Rails. It is very similar to PHP, JSP and ASP.


Tags for Embedding Ruby edit

  • <%= %> will render the result returned from the embedded Ruby expression as text
  • <% %> will execute the embedded expression without rendering the result
  • <% -%> will execute the embedded expression without rendering the result and will suppress trailing whitespace
  • <%- %> will execute the embedded expression without rendering the result and will suppress leading whitespace
  • <%# %> will cause the embedded expression to be parsed as a comment

ERb Utility Methods edit

There are a couple utility methods which are part of ERb that you may encounter when developing Rails applications:

  • h(s) or html_escape(s) - A utility method for escaping HTML tag characters in the supplied String s
  • u(s) or url_encode(s) - A utility method for encoding the String s as a URL

Example edit


  <h1>People</h1>
    
  <ul>
    <% @people.each do |person| -%>
    <li><%= person.first_name %></li>
    <% end -%>
  </ul>

If @people contained an array of Person instances, this would render something like the following:


  <h1>People</h1>

  <ul>
    <li>Bob</li>
    <li>Joe</li>
    <li>Mary</li>
  </ul>

Tips edit

  • While it is possible to put business logic in the view this should be avoided. Business logic belongs in the model where it can be easily tested and reused.
  • The line <%= render :partial => '/layouts/menu' %> will render a the partial app/views/layouts/_menu.