Views

View Templates

All view templates are stored in app/views/controllername. The extension determines what kind of template it is:

*.html.erb

Ruby HTML (using wish.name_and_quantity)

*.xml.erb

Ruby XML (using Builder)

*.rjs

Ruby JavaScript

All instance variables of the controller are available to the view. In addition, the following special objects can be accessed:

headers

The headers of the outgoing response

request

The incoming request object

response

The outgoing response object

params

The parameter hash

session

The session hash

controller

The current controller

html.erb

html.erb is HTML mixed with Ruby, by using tags. All of Ruby is available for programming:

<% %>   # executes the Ruby code
<%= %>  # executes the Ruby code and displays the result

<ul>
<% @products.each do |p| %>
  <li><%= h @p.name %></li>
<% end %>
</ul>

The output of anything in <%= %> tags is directly copied to the HTML output stream. To secure against HTML injection, use the h() function to HTML-escape the output. For example:

<%=h @user_entered_notes %>

xml.erb

Creates XML files:

xml.instruct! # <?xml version="1.0" encoding="UTF-8"?> xml.comment! "a comment" # <!-- a comment --> xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do xml.title "My Atom Feed" xml.subtitle h(@feed.subtitle), "type" => 'html' xml.link url_for( :only_path => false, :controller => 'feed', :action => 'atom' ) xml.updated @updated.iso8601 xml.author do xml.name "Jens-Christian Fischer" xml.email "jcfischer@gmail.com" end @entries.each do |entry| xml.entry do ...

Get Rails: Up and Running, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.