aboutsummaryrefslogblamecommitdiffstats
path: root/railties/guides/source/action_view_overview.textile
blob: 8b5eda0973b98ce1273e6eb59d59ec1187f20c74 (plain) (tree)
1
2
3
4
5
6
7
8
9



                             




                                                                    




                        
                                                                                                                                                                                                                                                                                                                                                                                                                                           



                                                                                                                                                                                                                                                                                                 






                                      








                                                                                                                                                                                                                                                                                                                                   
                                                                                                               




                  
                                                    





                                                                
                                                              

       
                                                                                                           




                   

                                                                































                                                                                                                          
 

                                                                



                                   

                                                                 





                                                            






























                                                                                                                                                                                     
                       





                                        
      




                                    
       








                                                                                                                                                                                                        
                         





                                                                                                            




              
                                                       
 

                                                                                                                                                                                                                                                
                      


                                                                                                                                                                              
                    






                                                                                                 
                      






                                                                                                                                  
        






                                                                                                                                                                                                                                                                                                     
      










                                                                                          
       


                                                                                                                       
         









                                                                                                      
                  









                                                                                                                                                                                                                                                                                                           
                                 











                                                                                                                                                                                                                                                             
                                       


                                                                                                                                                                                                                                                                                  
                                 











                                                                                                                                                                                                                                                              
                           







                                                                                                         
              






                                                                                                                                                                                     
             






                                                                                                                              
                          


























                                                                                                                                                                                                                                                                                                                                                                             
                   






                                                                                                                                                                                                                                                                               
                       




















                                                                                                                                                                                                                                                                                                                                                                
                   






                                                                                                                                                                                                                                                                           
                  
 
             









































                                                                          
                   
 
             










                                                                                                                                                                                                                 
               
 
         








                                                                                                                                                                                                                                                                                                                                  
                 
 
           





















                                                                                                                                                   
               




























                                                                                                                                                                                                                                                                                 
              







































































































































                                                                                                                                                                                                                          
               


















                                                                                                          
              








                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
                                                                        







































                                                                                                                                                                                                     
                                                                         


                                                       
                                                             


















                                                                                                                             
                            

































































                                                                                                          
                     























































































































































                                                                                                                                                                                                                     
                 
 
                                                                                                                                                                                                   
 
                 
 
                                   
 









                                                                    
                       











                                                                                                   
                                                                

                                                                       
         













                                                                                                                                
                           
                                     
         























































































                                                                                                                                                   
                                                                                                                                                                                                                                                                                                                                                                                                           










































































































































































                                                                                                                                                                                                                                                                                                                                                                                              
                                    



















































                                                                                                                                                                                                                                                                             
             






                                              
           




































































































                                                                                                                                                                      
                             




























                                                                                                                                                                                     
 
                                                                                                          

 
                                          
 






                                                                                                                                                                                                                                                                                                                                                                                                                                                                  











                                                                                                                                                                                                                                                                                                                                            
                                                                                                                             






                                                                                         
                                                                                                                                                                                                                                      
                                                                               
h2. Action View Overview

In this guide you will learn:

* What Action View is, and how to use it with Rails
* How to use Action View outside of Rails
* How best to use templates, partials, and layouts
* What helpers are provided by Action View, and how to make your own
* How to use localized views

endprologue.

h3. What is Action View?

Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. 

Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. 

Note: Some features of Action View are tied to Active Record, but that doesn't mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.

h3. Using Action View with Rails

TODO...

h3. Using Action View outside of Rails

Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small "Rack":http://rack.rubyforge.org/ application that includes Action View functionality. This may be useful, for example, if you'd like access to Action View's helpers in a Rack application. 

Let's start by ensuring that you have the Action Pack and Rack gems installed:

<shell>
gem install actionpack
gem install rack
</shell>

Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Active Support.

*hello_world.rb:*

<ruby>
require 'rubygems'
require 'active_support/core_ext/string/inflections'
require 'rack'

def hello_world(env)
  [200, {"Content-Type" => "text/html"}, "hello world".titleize]
end

Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
</ruby>

We can see this all come together by starting up the application and then visiting +http://localhost:4567/+

<shell>
ruby hello_world.rb
</shell>

TODO needs a screenshot? I have one - not sure where to put it. 

Notice how 'hello world' has been converted into 'Hello World' by the +titleize+ helper method. 

Action View can also be used with "Sinatra":http://www.sinatrarb.com/ in the same way. 

Let's start by ensuring that you have the Action Pack and Sinatra gems installed:

<shell>
gem install actionpack
gem install sinatra
</shell>

Now we'll create the same "Hello World" application in Sinatra.

*hello_world.rb:*

<ruby>
require 'rubygems'
require 'action_view'
require 'sinatra'

get '/' do
  erb 'hello world'.titleize
end
</ruby>

Then, we can run the application:

<shell>
ruby hello_world.rb
</shell>

Once the application is running, you can see Sinatra and Action View working together by visiting +http://localhost:4567/+

TODO needs a screenshot? I have one - not sure where to put it. 

h3. Templates, Partials and Layouts

TODO...

TODO see http://guides.rubyonrails.org/layouts_and_rendering.html

h3. Using Templates, Partials and Layouts in "The Rails Way"

TODO...

h3. Partial Layouts

Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.

Let's say we're displaying a post on a page where it should be wrapped in a +div+ for display purposes. First, we'll create a new +Post+:

<ruby>
Post.create(:body => 'Partial Layouts are cool!')
</ruby>

In the +show+ template, we'll render the +post+ partial wrapped in the +box+ layout:

*posts/show.html.erb*

<ruby>
<%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %>
</ruby>

The +box+ layout simply wraps the +post+ partial in a +div+:

*posts/_box.html.erb*

<ruby>
<div class='box'>
  <%= yield %>
</div>
</ruby>

The +post+ partial wraps the post's +body+ in a +div+ with the +id+ of the post using the +div_for+ helper:

*posts/_post.html.erb*

<ruby>
<%= div_for(post) do %>
  <p><%= post.body %></p>
<% end %>
</ruby>

This example would output the following:

<html>
<div class='box'>
  <div id='post_1'>
    <p>Partial Layouts are cool!</p>
  </div>
</div>
</html>

Note that the partial layout has access to the local +post+ variable that was passed into the +render+ call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.

You can also render a block of code within a partial layout instead of calling +yield+. For example, if we didn't have the +post+ partial, we could do this instead:

*posts/show.html.erb*

<ruby>
<% render(:layout => 'box', :locals => {:post => @post}) do %>
  <%= div_for(post) do %>
    <p><%= post.body %></p>
  <% end %>
<% end %>
</ruby>

If we're using the same +box+ partial from above, his would produce the same output as the previous example.

h3. View Paths

TODO...

h3. Overview of all the helpers provided by Action View

The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point. 

h4. ActiveRecordHelper

The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the "Rails Form helpers guide":form_helpers.html.

h5. error_message_on

Returns a string containing the error message attached to the method on the object if one exists.

<ruby>
error_message_on "post", "title"
</ruby>

h5. error_messages_for

Returns a string with a DIV containing all of the error messages for the objects located as instance variables by the names given.

<ruby>
error_messages_for "post"
</ruby>

h5. form

Returns a form with inputs for all attributes of the specified Active Record object. For example, let's say we have a +@post+ with attributes named +title+ of type +String+ and +body+ of type +Text+. Calling +form+ would produce a form to creating a new post with inputs for those attributes. 

<ruby>
form("post")
</ruby>

<html>
<form action='/posts/create' method='post'>
  <p>
    <label for="post_title">Title</label><br />
    <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
  </p>
  <p>
    <label for="post_body">Body</label><br />
    <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
  </p>
  <input name="commit" type="submit" value="Create" />
</form>
</html>

Typically, +form_for+ is used instead of +form+ because it doesn't automatically include all of the model's attributes.

h5. input

Returns a default input tag for the type of object returned by the method. 

For example, if +@post+ has an attribute +title+ mapped to a +String+ column that holds "Hello World":

<ruby>
input("post", "title") # => 
  <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
</ruby>

h4. AssetTagHelper

This module provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds. 

By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting +ActionController::Base.asset_host+ in your +config/environment.rb+. For example, let's say your asset host is +assets.example.com+:

<ruby>
ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" /> 
</ruby>

h5. register_javascript_expansion

Register one or more javascript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register javascript files that the plugin installed in public/javascripts.

<ruby>
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]

javascript_include_tag :monkey # =>
  <script type="text/javascript" src="/javascripts/head.js"></script>
  <script type="text/javascript" src="/javascripts/body.js"></script>
  <script type="text/javascript" src="/javascripts/tail.js"></script>
</ruby>

h5. register_javascript_include_default

Register one or more additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ files that the plugin installed in +public/javascripts+.

h5. register_stylesheet_expansion

Register one or more stylesheet files to be included when symbol is passed to +stylesheet_link_tag+. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in +public/stylesheets+.

<ruby>
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]

stylesheet_link_tag :monkey # =>
  <link href="/stylesheets/head.css"  media="screen" rel="stylesheet" type="text/css" />
  <link href="/stylesheets/body.css"  media="screen" rel="stylesheet" type="text/css" />
  <link href="/stylesheets/tail.css"  media="screen" rel="stylesheet" type="text/css" />
</ruby>

h5. auto_discovery_link_tag

Returns a link tag that browsers and news readers can use to auto-detect an RSS or ATOM feed.

<ruby>
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
  <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
</ruby>

h5. image_path

Computes the path to an image asset in the public images directory. Full paths from the document root will be passed through. Used internally by +image_tag+ to build the image path.

<ruby>
image_path("edit.png") # => /images/edit.png
</ruby>

h5. image_tag

Returns an html image tag for the source. The source can be a full path or a file that exists in your public images directory.

<ruby>
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
</ruby>

h5. javascript_include_tag

Returns an html script tag for each of the sources provided. You can pass in the filename (+.js+ extension is optional) of javascript files that exist in your +public/javascripts+ directory for inclusion into the current page or you can pass the full path relative to your document root.

<ruby>
javascript_include_tag "common" # =>
  <script type="text/javascript" src="/javascripts/common.js"></script>  
</ruby>

To include the Prototype and Scriptaculous javascript libraries in your application, pass +:defaults+ as the source. When using +:defaults+, if an +application.js+ file exists in your +public/javascripts+ directory, it will be included as well. 

<ruby>
javascript_include_tag :defaults
</ruby>

You can also include all javascripts in the javascripts directory using +:all+ as the source.

<ruby>
javascript_include_tag :all
</ruby>

You can also cache multiple javascripts into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if +ActionController::Base.perform_caching+ is set to true (which is the case by default for the Rails production environment, but not for the development environment).

<ruby>
javascript_include_tag :all, :cache => true # => 
  <script type="text/javascript" src="/javascripts/all.js"></script>  
</ruby>

h5. javascript_path

Computes the path to a javascript asset in the +public/javascripts+ directory. If the source filename has no extension, +.js+ will be appended. Full paths from the document root will be passed through. Used internally by +javascript_include_tag+ to build the script path.

<ruby>
javascript_path "common" # => /javascripts/common.js
</ruby>

h5. stylesheet_link_tag

Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, +.css+ will be appended automatically. 

<ruby>
stylesheet_link_tag "application" # =>
  <link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
</ruby>

You can also include all styles in the stylesheet directory using :all as the source:

<ruby>
stylesheet_link_tag :all
</ruby>

You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). 

<ruby>
stylesheet_link_tag :all, :cache => true
  <link href="/stylesheets/all.css"  media="screen" rel="stylesheet" type="text/css" />
</ruby>

h5. stylesheet_path

Computes the path to a stylesheet asset in the public stylesheets directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.

<ruby>
stylesheet_path "application" # => /stylesheets/application.css
</ruby>

h4. AtomFeedHelper

h5. atom_feed

This helper makes building an ATOM feed easy. Here's a full usage example:

*config/routes.rb*

<ruby>
map.resources :posts
</ruby>

*app/controllers/posts_controller.rb*

<ruby>
def index
  @posts = Post.find(:all)

  respond_to do |format|
    format.html
    format.atom
  end
end
</ruby>

*app/views/posts/index.atom.builder*

<ruby>
atom_feed do |feed|
  feed.title("Posts Index")
  feed.updated((@posts.first.created_at))

  for post in @posts
    feed.entry(post) do |entry|
      entry.title(post.title)
      entry.content(post.body, :type => 'html')

      entry.author do |author|
        author.name(post.author_name)
      end
    end
  end
end
</ruby>

h4. BenchmarkHelper

h5. benchmark

Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.

<ruby>
<% benchmark "Process data files" do %>
  <%= expensive_files_operation %>
<% end %>  
</ruby>

This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.

h4. CacheHelper

h5. cache

A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See +ActionController::Caching::Fragments+ for more information.

<ruby>
<% cache do %>
  <%= render :partial => "shared/footer" %>
<% end %>
</ruby>

h4. CaptureHelper

h5. capture

The +capture+ method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.

<ruby>
<% @greeting = capture do %>
  <p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
<ruby>

The captured variable can then be used anywhere else.

<ruby>
<html>
  <head>
    <title>Welcome!</title>
  </head>
  <body>
    <%= @greeting %>
  </body>
</html>
</ruby>  

h5. content_for

Calling +content_for+ stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to +yield+.

For example, let's say we have a standard application layout, but also a special page that requires certain Javascript that the rest of the site doesn't need. We can use +content_for+ to include this Javascript on our special page without fattening up the rest of the site.

*app/views/layouts/application.html.erb*

<ruby>
<html>
  <head>
    <title>Welcome!</title>
    <%= yield :special_script %>
  </head>
  <body>
    <p>Welcome! The date and time is <%= Time.now %></p>
  </body>
</html>
</ruby>

*app/views/posts/special.html.erb*

<ruby>
<p>This is a special page.</p>

<% content_for :special_script do %>
  <script type="text/javascript">alert('Hello!')</script>
<% end %>  
</ruby>

h4. DateHelper

h5. date_select

Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.

<ruby>
date_select("post", "published_on")
</ruby>

h5. datetime_select

Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.

<ruby>
datetime_select("post", "published_on")
</ruby>

h5. distance_of_time_in_words

Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set +include_seconds+ to true if you want more detailed approximations.

<ruby>
distance_of_time_in_words(Time.now, Time.now + 15.seconds)        # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, true)  # => less than 20 seconds
</ruby>

h5. select_date

Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+ provided.

<ruby>
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)

# Generates a date select that defaults to today (no specified date)
select_date()  
</ruby>

h5. select_datetime

Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+ provided.

<ruby>
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)

# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()  
</ruby>

h5. select_day

Returns a select tag with options for each of the days 1 through 31 with the current day selected.

<ruby>
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)

# Generates a select field for days that defaults to the number given
select_day(5)
</ruby>

h5. select_hour

Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.

<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided
select_minute(Time.now + 6.hours)
</ruby>

h5. select_minute

Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.

<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
</ruby>

h5. select_month

Returns a select tag with options for each of the months January through December with the current month selected.

<ruby>
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</ruby>

h5. select_second

Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.

<ruby>
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)  
</ruby>

h5. select_time

Returns a set of html select-tags (one for hour and minute).

<ruby>
# Generates a time select that defaults to the time provided
select_time(Time.now)  
</ruby>

h5. select_year

Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the +:start_year+ and +:end_year+ keys in the +options+.

<ruby>
# Generates a select field for five years on either side of +Date.today+ that defaults to the current year
select_year(Date.today)

# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, :start_year => 1900, :end_year => 2009)
</ruby>

h5. time_ago_in_words

Like +distance_of_time_in_words+, but where +to_time+ is fixed to +Time.now+.

<ruby>
time_ago_in_words(3.minutes.from_now)       # => 3 minutes
</ruby>

h5. time_select

Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.

<ruby>
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")  
</ruby>

h4. DebugHelper

Returns a +pre+ tag that has object dumped by YAML. This creates a very readable way to inspect an object.

<ruby>
my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
debug(my_hash)
</ruby>

<html>
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
</html>

h4. FormHelper

Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.

There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don‘t work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.

The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:

<ruby>
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for :person, @person, :url => { :action => "create" } do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= submit_tag 'Create' %>
<% end %>
</ruby>

The HTML generated for this would be:

<html>
<form action="/persons/create" method="post">
  <input id="person_first_name" name="person[first_name]" size="30" type="text" />
  <input id="person_last_name" name="person[last_name]" size="30" type="text" />
  <input name="commit" type="submit" value="Create" />
</form>
</html>

The params object created when this form is submitted would look like:

<ruby>
{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
</ruby>

The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.

h5. check_box

Returns a checkbox tag tailored for accessing a specified attribute.

<ruby>
# Let's say that @post.validated? is 1:
check_box("post", "validated")
# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
#    <input name="post[validated]" type="hidden" value="0" />
</ruby>

h5. fields_for

Creates a scope around a specific model object like form_for, but doesn‘t create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:

<ruby>
<%= form_for @person, :url => { :action => "update" } do |person_form| %>
  First name: <%= person_form.text_field :first_name %>
  Last name : <%= person_form.text_field :last_name %>

  <%= fields_for @person.permission do |permission_fields| %>
    Admin?  : <%= permission_fields.check_box :admin %>
  <% end %>
<% end %>
</ruby>

h5. file_field

Returns an file upload input tag tailored for accessing a specified attribute.

<ruby>
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />  
</ruby>

h5. form_for

Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.

<ruby>
<%= form_for @post do |f| %>
  <%= f.label :title, 'Title' %>:
  <%= f.text_field :title %><br />
  <%= f.label :body, 'Body' %>:
  <%= f.text_area :body %><br />
<% end %>
</ruby>

h5. hidden_field

Returns a hidden input tag tailored for accessing a specified attribute.

<ruby>
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />  
</ruby>

h5. label

Returns a label tag tailored for labelling an input field for a specified attribute.

<ruby>
label(:post, :title)
# => <label for="post_title">Title</label>
</ruby>

h5. password_field

Returns an input tag of the "password" type tailored for accessing a specified attribute.

<ruby>
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />  
</ruby>

h5. radio_button

Returns a radio button tag for accessing a specified attribute.

<ruby>
# Let's say that @post.category returns "rails":
radio_button("post", "category", "rails")
radio_button("post", "category", "java")
# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
#    <input type="radio" id="post_category_java" name="post[category]" value="java" />
</ruby>

h5. text_area

Returns a textarea opening and closing tag set tailored for accessing a specified attribute.

<ruby>
text_area(:comment, :text, :size => "20x30")
# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
#      #{@comment.text}
#    </textarea>
</ruby>

h5. text_field

Returns an input tag of the "text" type tailored for accessing a specified attribute.

<ruby>
text_field(:post, :title)
# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
</ruby>

h4. FormOptionsHelper

Provides a number of methods for turning different kinds of containers into a set of option tags.

h5. collection_select

Returns +select+ and +option+ tags for the collection of existing return values of +method+ for +object+'s class.

Example object structure for use with this method:

<ruby>
class Post < ActiveRecord::Base
  belongs_to :author
end

class Author < ActiveRecord::Base
  has_many :posts
  def name_with_initial
    "#{first_name.first}. #{last_name}"
  end
end
</ruby>

Sample usage (selecting the associated Author for an instance of Post, +@post+):

<ruby>
collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
</ruby>

If @post.author_id is already 1, this would return:

<html>
<select name="post[author_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">D. Heinemeier Hansson</option>
  <option value="2">D. Thomas</option>
  <option value="3">M. Clark</option>
</select>
</html>

h5. country_options_for_select

Returns a string of option tags for pretty much any country in the world.

h5. country_select

Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.

h5. option_groups_from_collection_for_select

Returns a string of +option+ tags, like +options_from_collection_for_select+, but groups them by +optgroup+ tags based on the object relationships of the arguments.

Example object structure for use with this method:

<ruby>
class Continent < ActiveRecord::Base
  has_many :countries
  # attribs: id, name
end

class Country < ActiveRecord::Base
  belongs_to :continent
  # attribs: id, name, continent_id
end
</ruby>

Sample usage:

<ruby>  
option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
</ruby>

TODO check above textile output looks right

Possible output:

<html>
<optgroup label="Africa">
  <option value="1">Egypt</option>
  <option value="4">Rwanda</option>
  ...
</optgroup>
<optgroup label="Asia">
  <option value="3" selected="selected">China</option>
  <option value="12">India</option>
  <option value="5">Japan</option>
  ...
</optgroup>
</html>

Note: Only the +optgroup+ and +option+ tags are returned, so you still have to wrap the output in an appropriate +select+ tag.

h5. options_for_select

Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. 

<ruby>
options_for_select([ "VISA", "MasterCard" ])
# => <option>VISA</option> <option>MasterCard</option>
</ruby>

Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.

h5. options_from_collection_for_select

Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.

<ruby>
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
</ruby>

For example, imagine a loop iterating over each person in @project.people to generate an input tag:

<ruby>
options_from_collection_for_select(@project.people, "id", "name")
# => <option value="#{person.id}">#{person.name}</option>
</ruby> 

Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.

h5. select

Create a select tag and a series of contained option tags for the provided object and method.

Example with @post.person_id => 1:

<ruby>
select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>

could become:

<html>
<select name="post[person_id]">
  <option value=""></option>
  <option value="1" selected="selected">David</option>
  <option value="2">Sam</option>
  <option value="3">Tobias</option>
</select>
</html>

h5. time_zone_options_for_select

Returns a string of option tags for pretty much any time zone in the world.

h5. time_zone_select

Return select and option tags for the given object and method, using +time_zone_options_for_select+ to generate the list of option tags.

<ruby>
time_zone_select( "user", "time_zone")
</ruby>

h4. FormTagHelper

Provides a number of methods for creating form tags that doesn't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.

h5. check_box_tag

Creates a check box form input tag.

<ruby>
check_box_tag 'accept'
# => <input id="accept" name="accept" type="checkbox" value="1" />  
</ruby>

h5. field_set_tag

Creates a field set for grouping HTML form elements.

<ruby>
<%= field_set_tag do %>
  <p><%= text_field_tag 'name' %></p>
<% end %>
# => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
</ruby>

h5. file_field_tag

Creates a file upload field. 

If you are using file uploads then you will also need to set the multipart option for the form tag:

<ruby>
<%= form_tag { :action => "post" }, { :multipart => true } do %>
  <label for="file">File to Upload</label> <%= file_field_tag "file" %>
  <%= submit_tag %>
<% end %>
</ruby>

Example output:

<ruby>
file_field_tag 'attachment'
# => <input id="attachment" name="attachment" type="file" />
</ruby>

h5. form_tag

Starts a form tag that points the action to an url configured with +url_for_options+ just like +ActionController::Base#url_for+.

<ruby>
<%= form_tag '/posts' do %>
  <div><%= submit_tag 'Save' %></div>
<% end %>
# => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
</ruby>

h5. hidden_field_tag

Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user.

<ruby>
hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
# => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
</ruby>

h5. image_submit_tag

Displays an image which when clicked will submit the form.

<ruby>
image_submit_tag("login.png")
# => <input src="/images/login.png" type="image" />
</ruby>

h5. label_tag

Creates a label field.

<ruby>
label_tag 'name'
# => <label for="name">Name</label>
</ruby>

h5. password_field_tag

Creates a password field, a masked text field that will hide the users input behind a mask character.

<ruby>
password_field_tag 'pass'
# => <input id="pass" name="pass" type="password" />
</ruby>

h5. radio_button_tag

Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options.

<ruby>
radio_button_tag 'gender', 'male'
# => <input id="gender_male" name="gender" type="radio" value="male" />
</ruby>

h5. select_tag

Creates a dropdown selection box.

<ruby>
select_tag "people", "<option>David</option>"
# => <select id="people" name="people"><option>David</option></select>
</ruby>

h5. submit_tag

Creates a submit button with the text provided as the caption.

<ruby>
submit_tag "Publish this post"
# => <input name="commit" type="submit" value="Publish this post" />
</ruby>

h5. text_area_tag

Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.

<ruby>
text_area_tag 'post'
# => <textarea id="post" name="post"></textarea>
</ruby>

h5. text_field_tag

Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.

<ruby>
text_field_tag 'name'
# => <input id="name" name="name" type="text" />
</ruby>

h4. JavaScriptHelper

Provides functionality for working with JavaScript in your views.

Rails includes the Prototype JavaScript framework and the Scriptaculous JavaScript controls and visual effects library. If you wish to use these libraries and their helpers, make sure +&lt;%= javascript_include_tag :defaults, :cache => true %&gt;+ is in the HEAD section of your page. This function will include the necessary JavaScript files Rails generated in the public/javascripts directory.

h5. button_to_function

Returns a button that'll trigger a JavaScript function using the onclick handler. Examples:

<ruby>
button_to_function "Greeting", "alert('Hello world!')"
button_to_function "Delete", "if (confirm('Really?')) do_delete()"
button_to_function "Details" do |page|
  page[:details].visual_effect :toggle_slide
end
</ruby>

h5. define_javascript_functions

Includes the Action Pack JavaScript libraries inside a single +script+ tag.

h5. escape_javascript

Escape carrier returns and single and double quotes for JavaScript segments.

h5. javascript_tag

Returns a JavaScript tag wrapping the provided code.

<ruby>
javascript_tag "alert('All is good')"
</ruby>

<html>
<script type="text/javascript">
//<![CDATA[
alert('All is good')
//]]>
</script>
</html>

h5. link_to_function

Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.

<ruby>
link_to_function "Greeting", "alert('Hello world!')"
# => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
</ruby>

h4. NumberHelper

Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.

h5. number_to_currency

Formats a number into a currency string (e.g., $13.65).

<ruby>
number_to_currency(1234567890.50) # => $1,234,567,890.50
</ruby>

h5. number_to_human_size

Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users.

<ruby>
number_to_human_size(1234)          # => 1.2 KB
number_to_human_size(1234567)       # => 1.2 MB
</ruby>

h5. number_to_percentage

Formats a number as a percentage string.

<ruby>
number_to_percentage(100, :precision => 0)        # => 100%
</ruby>

h5. number_to_phone

Formats a number into a US phone number.

<ruby>
number_to_phone(1235551234) # => 123-555-1234
</ruby>

h5. number_with_delimiter

Formats a number with grouped thousands using a delimiter.

<ruby>
number_with_delimiter(12345678) # => 12,345,678
</ruby>

h5. number_with_precision

Formats a number with the specified level of +precision+, which defaults to 3. 

<ruby>
number_with_precision(111.2345)     # => 111.235
number_with_precision(111.2345, 2)  # => 111.23
</ruby>

h4. PrototypeHelper

Prototype is a JavaScript library that provides DOM manipulation, Ajax functionality, and more traditional object-oriented facilities for JavaScript. This module provides a set of helpers to make it more convenient to call functions from Prototype using Rails, including functionality to call remote Rails methods (that is, making a background request to a Rails action) using Ajax.

To be able to use these helpers, you must first include the Prototype JavaScript framework in the HEAD of the pages with Prototype functions.

<ruby>
javascript_include_tag 'prototype'
</ruby>

h5. evaluate_remote_response

Returns +eval(request.responseText)+ which is the JavaScript function that form_remote_tag can call in +:complete+ to evaluate a multiple update return document using +update_element_function+ calls.

h5. form_remote_tag

Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement. Even though it‘s using JavaScript to serialize the form elements, the form submission will work just like a regular submission as viewed by the receiving side.

For example, this:

<ruby>
form_remote_tag :html => { :action => url_for(:controller => "some", :action => "place") }
</ruby>

would generate the following:

<html>
<form action="/some/place" method="post" onsubmit="new Ajax.Request('', 
  {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
</html>

h5. link_to_remote

Returns a link to a remote action that's called in the background using XMLHttpRequest. You can generate a link that uses AJAX in the general case, while degrading gracefully to plain link behavior in the absence of JavaScript. For example:

<ruby>
link_to_remote "Delete this post",
  { :update => "posts", :url => { :action => "destroy", :id => post.id } },
  :href => url_for(:action => "destroy", :id => post.id)
</ruby>

h5. observe_field

Observes the field specified and calls a callback when its contents have changed.

<ruby>
observe_field("my_field", :function => "alert('Field changed')")
</ruby>

h5. observe_form

Observes the form specified and calls a callback when its contents have changed. The options for observe_form are the same as the options for observe_field.

<ruby>
observe_field("my_form", :function => "alert('Form changed')")
</ruby>

h5. periodically_call_remote

Periodically calls the specified url as often as specified. Usually used to update a specified div with the results of the remote call. The following example will call update every 20 seconds and update the news_block div:

<ruby>
periodically_call_remote(:url => 'update', :frequency => '20', :update => 'news_block')
# => PeriodicalExecuter(function() {new Ajax.Updater('news_block', 'update', {asynchronous:true, evalScripts:true})}, 20)
</ruby>

h5. remote_form_for

Creates a form that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement and a scope around a specific resource that is used as a base for questioning about values for the fields.

<ruby>
<%= remote_form_for(@post) do |f| %>
  ...
<% end %>
</ruby>

h5. remote_function

Returns the JavaScript needed for a remote function. Takes the same arguments as +link_to_remote+.

<ruby>
<select id="options" onchange="<%= remote_function(:update => "options", :url => { :action => :update_options }) %>">
  <option value="0">Hello</option>
  <option value="1">World</option>
</select>
# => <select id="options" onchange="new Ajax.Updater('options', '/testing/update_options', {asynchronous:true, evalScripts:true})">
</ruby>

h5. submit_to_remote

Returns a button input tag that will submit form using XMLHttpRequest in the background instead of a regular POST request that reloads the page.

For example, the following:

<ruby>
submit_to_remote 'create_btn', 'Create', :url => { :action => 'create' }
</ruby>

would generate:

<html>
<input name="create_btn" onclick="new Ajax.Request('/testing/create',
  {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});
  return false;" type="button" value="Create" />
</html>

h5. update_page

Yields a JavaScriptGenerator and returns the generated JavaScript code. Use this to update multiple elements on a page in an Ajax response.

<ruby>
update_page do |page|
  page.hide 'spinner'
end  
</ruby>

h5. update_page_tag

Works like update_page but wraps the generated JavaScript in a +script+ tag. Use this to include generated JavaScript in an ERb template.

h4. PrototypeHelper::JavaScriptGenerator::GeneratorMethods

JavaScriptGenerator generates blocks of JavaScript code that allow you to change the content and presentation of multiple DOM elements. Use this in your Ajax response bodies, either in a +script+ tag or as plain JavaScript sent with a Content-type of "text/javascript".

h5(#push). <<

Writes raw JavaScript to the page.

<ruby>
page << "alert('JavaScript with Prototype.');"
</ruby>

h5(#at). []

Returns a element reference by finding it through it's id in the DOM.

<ruby>
page['blank_slate'].show # => $('blank_slate').show();
</ruby>

h5. alert

Displays an alert dialog with the given message.

<ruby>
page.alert('This message is from Rails!')
</ruby>

h5. assign

Assigns the JavaScript variable the given value.

<ruby>
page.assign 'tabulated_total', @total_from_cart
</ruby>

h5. call

Calls the JavaScript function, optionally with the given arguments.

<ruby>
page.call 'Element.replace', 'my_element', "My content to replace with."
</ruby>

h5. delay

Executes the content of the block after a delay of the number of seconds provided.

<ruby>
page.delay(20) do
  page.visual_effect :fade, 'notice'
end
</ruby>

h5. draggable

Creates a script.aculo.us draggable element. See ActionView::Helpers::ScriptaculousHelper for more information.

h5. drop_receiving

Creates a script.aculo.us drop receiving element. See ActionView::Helpers::ScriptaculousHelper for more information.

h5. hide

Hides the visible DOM elements with the given ids.

<ruby>
page.hide 'person_29', 'person_9', 'person_0'
</ruby>

h5. insert_html

Inserts HTML at the specified position relative to the DOM element identified by the given id.

<ruby>
page.insert_html :bottom, 'my_list', '<li>Last item</li>'
</ruby>

h5. literal

Returns an object whose to_json evaluates to the code provided. Use this to pass a literal JavaScript expression as an argument to another JavaScriptGenerator method.

h5. redirect_to

Redirects the browser to the given location using JavaScript, in the same form as +url_for+.

<ruby>
page.redirect_to(:controller => 'accounts', :action => 'new')
</ruby>

h5. remove

Removes the DOM elements with the given ids from the page.

<ruby>
page.remove 'person_23', 'person_9', 'person_2'  
</ruby>

h5. replace

Replaces the "outer HTML" (i.e., the entire element, not just its contents) of the DOM element with the given id.

<ruby>
page.replace 'person-45', :partial => 'person', :object => @person
</ruby>

h5. replace_html

Replaces the inner HTML of the DOM element with the given id.

<ruby>
page.replace_html 'person-45', :partial => 'person', :object => @person
</ruby>

h5(#prototype-select). select

Returns a collection reference by finding it through a CSS pattern in the DOM.

<ruby>
page.select('p.welcome b').first.hide # => $$('p.welcome b').first().hide();
</ruby>  

h5. show

Shows hidden DOM elements with the given ids.

<ruby>
page.show 'person_6', 'person_13', 'person_223'
</ruby>

h5. sortable

Creates a script.aculo.us sortable element. Useful to recreate sortable elements after items get added or deleted. See ActionView::Helpers::ScriptaculousHelper for more information.

h5. toggle

Toggles the visibility of the DOM elements with the given ids. Example:

<ruby>
page.toggle 'person_14', 'person_12', 'person_23'      # Hides the elements
page.toggle 'person_14', 'person_12', 'person_23'      # Shows the previously hidden elements  
</ruby>

h5. visual_effect

Starts a script.aculo.us visual effect. See ActionView::Helpers::ScriptaculousHelper for more information.


TODO start from RecordIdentificationHelper


h3. Localized Views

Action View has the ability render different templates depending on the current locale.

For example, suppose you have a Posts controller with a show action. By default, calling this action will render +app/views/posts/show.html.erb+. But if you set +I18n.locale = :de+, then +app/views/posts/show.de.html.erb+ will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. 

You can use the same technique to localize the rescue files in your public directory. For example, setting +I18n.locale = :de+ and creating +public/500.de.html+ and +public/404.de.html+ would allow you to have localized rescue pages.

Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to +app/controllers/application.rb+: 

<ruby>
before_filter :set_expert_locale

def set_expert_locale
  I18n.locale = :expert if current_user.expert?
end
</ruby>

Then you could create special views like +app/views/posts/show.expert.html.erb+ that would only be displayed to expert users.

You can read more about the Rails Internationalization (I18n) API "here":i18n.html. 

h3. Changelog

"Lighthouse Ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/71

* September 3, 2009: Continuing work by Trevor Turk, leveraging the "Action Pack docs":http://ap.rubyonrails.org/ and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts
* April 5, 2009: Starting work by Trevor Turk, leveraging Mike Gunderloy's docs