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
For each controller there is an associated directory in the app/views directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:
<% end %>
A product of Danish Design during the Winter of '79...
Here are a few of our fine products:
<% @products.each do |product| %> <%= render :partial => "product", :locals => { :product => product } %> <% end %> <%= render "shared/footer" %><%= post.body %>
<% end %> This example would output the following:Partial Layouts are cool!
<%= post.body %>
<% end %> <% end %> 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. error_message_on "post", "title" 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. error_messages_for "post" 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. form("post") 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": input("post", "title") # => h4. RecordTagHelper This module provides methods for generating a container tag, such as a + 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+.
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
  
  
  
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+.
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
  
  
  
h5. auto_discovery_link_tag
Returns a link tag that browsers and news readers can use to auto-detect an RSS or Atom feed.
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
  
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.
image_path("edit.png") # => /images/edit.png
h5. image_url
Computes the url to an image asset in the +public/images+ directory. This will call +image_path+ internally and merge with your current host or your asset host.
image_url("edit.png") # => http://www.example.com/images/edit.png
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.
image_tag("icon.png") # =>
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+.
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
  
  
  
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+.
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
  
  
  
h5. auto_discovery_link_tag
Returns a link tag that browsers and news readers can use to auto-detect an RSS or Atom feed.
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
  
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.
image_path("edit.png") # => /images/edit.png
h5. image_url
Computes the url to an image asset in the +public/images+ directory. This will call +image_path+ internally and merge with your current host or your asset host.
image_url("edit.png") # => http://www.example.com/images/edit.png
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.
image_tag("icon.png") # =>  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.
javascript_include_tag "common" # =>
  
If the application does not use the asset pipeline, to include the jQuery JavaScript library 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.
javascript_include_tag :defaults
You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
javascript_include_tag :all
You can also cache multiple JavaScript files 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).
javascript_include_tag :all, :cache => true # =>
  
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.
javascript_path "common" # => /javascripts/common.js
h5. javascript_url
Computes the url to a JavaScript asset in the +public/javascripts+ directory. This will call +javascript_path+ internally and merge with your current host or your asset host.
javascript_url "common" # => http://www.example.com/javascripts/common.js
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.
stylesheet_link_tag "application" # =>
  
You can also include all styles in the stylesheet directory using :all as the source:
stylesheet_link_tag :all
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).
stylesheet_link_tag :all, :cache => true
  
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.
stylesheet_path "application" # => /stylesheets/application.css
h5. stylesheet_url
Computes the url to a stylesheet asset in the +public/stylesheets+ directory. This will call +stylesheet_path+ internally and merge with your current host or your asset host.
stylesheet_url "application" # => http://www.example.com/stylesheets/application.css
h4. AtomFeedHelper
h5. atom_feed
This helper makes building an Atom feed easy. Here's a full usage example:
*config/routes.rb*
resources :posts
*app/controllers/posts_controller.rb*
def index
  @posts = Post.all
  respond_to do |format|
    format.html
    format.atom
  end
end
*app/views/posts/index.atom.builder*
atom_feed do |feed|
  feed.title("Posts Index")
  feed.updated((@posts.first.created_at))
  @posts.each do |post|
    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
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.
<% benchmark "Process data files" do %>
  <%= expensive_files_operation %>
<% end %>
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.
<% cache do %>
  <%= render "shared/footer" %>
<% end %>
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.
<% @greeting = capture do %>
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.
javascript_include_tag "common" # =>
  
If the application does not use the asset pipeline, to include the jQuery JavaScript library 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.
javascript_include_tag :defaults
You can also include all JavaScript files in the +public/javascripts+ directory using +:all+ as the source.
javascript_include_tag :all
You can also cache multiple JavaScript files 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).
javascript_include_tag :all, :cache => true # =>
  
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.
javascript_path "common" # => /javascripts/common.js
h5. javascript_url
Computes the url to a JavaScript asset in the +public/javascripts+ directory. This will call +javascript_path+ internally and merge with your current host or your asset host.
javascript_url "common" # => http://www.example.com/javascripts/common.js
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.
stylesheet_link_tag "application" # =>
  
You can also include all styles in the stylesheet directory using :all as the source:
stylesheet_link_tag :all
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).
stylesheet_link_tag :all, :cache => true
  
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.
stylesheet_path "application" # => /stylesheets/application.css
h5. stylesheet_url
Computes the url to a stylesheet asset in the +public/stylesheets+ directory. This will call +stylesheet_path+ internally and merge with your current host or your asset host.
stylesheet_url "application" # => http://www.example.com/stylesheets/application.css
h4. AtomFeedHelper
h5. atom_feed
This helper makes building an Atom feed easy. Here's a full usage example:
*config/routes.rb*
resources :posts
*app/controllers/posts_controller.rb*
def index
  @posts = Post.all
  respond_to do |format|
    format.html
    format.atom
  end
end
*app/views/posts/index.atom.builder*
atom_feed do |feed|
  feed.title("Posts Index")
  feed.updated((@posts.first.created_at))
  @posts.each do |post|
    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
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.
<% benchmark "Process data files" do %>
  <%= expensive_files_operation %>
<% end %>
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.
<% cache do %>
  <%= render "shared/footer" %>
<% end %>
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.
<% @greeting = capture do %>
  Welcome! The date and time is <%= Time.now %>
<% end %> The captured variable can then be used anywhere else.Welcome! The date and time is <%= Time.now %>
*app/views/posts/special.html.erb*This is a special page.
<% content_for :special_script do %> <% end %> 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. date_select("post", "published_on") 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. datetime_select("post", "published_on") 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. 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 h5. select_date Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+ provided. # 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() h5. select_datetime Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+ provided. # 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() h5. select_day Returns a select tag with options for each of the days 1 through 31 with the current day selected. # 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) h5. select_hour Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. # Generates a select field for minutes that defaults to the minutes for the time provided select_minute(Time.now + 6.hours) h5. select_minute Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. # Generates a select field for minutes that defaults to the minutes for the time provided. select_minute(Time.now + 6.hours) h5. select_month Returns a select tag with options for each of the months January through December with the current month selected. # Generates a select field for months that defaults to the current month select_month(Date.today) h5. select_second Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. # Generates a select field for seconds that defaults to the seconds for the time provided select_second(Time.now + 16.minutes) h5. select_time Returns a set of html select-tags (one for hour and minute). # Generates a time select that defaults to the time provided select_time(Time.now) 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+. # 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) h5. time_ago_in_words Like +distance_of_time_in_words+, but where +to_time+ is fixed to +Time.now+. time_ago_in_words(3.minutes.from_now) # => 3 minutes 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. # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute time_select("order", "submitted") h4. DebugHelper Returns a +pre+ tag that has object dumped by YAML. This creates a very readable way to inspect an object. my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]} debug(my_hash)--- first: 1 second: two third: - 1 - 2 - 3h4. 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: # Note: a @person variable will have been created in the controller (e.g. @person = Person.new) <%= form_for @person, :url => { :action => "create" } do |f| %> <%= f.text_field :first_name %> <%= f.text_field :last_name %> <%= submit_tag 'Create' %> <% end %> The HTML generated for this would be: The params object created when this form is submitted would look like: {"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}} 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. # Let's say that @post.validated? is 1: check_box("post", "validated") # => # 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: <%= 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 %> h5. file_field Returns a file upload input tag tailored for accessing a specified attribute. file_field(:user, :avatar) # => 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. <%= form_for @post do |f| %> <%= f.label :title, 'Title' %>: <%= f.text_field :title %>
<%= text_field_tag 'name' %>
<% end %> # => h5. file_field_tag Creates a file upload field. Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically. <%= form_tag { :action => "post" }, { :multipart => true } do %> <%= file_field_tag "file" %> <%= submit_tag %> <% end %> Example output: file_field_tag 'attachment' # => 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+. <%= form_tag '/posts' do %>