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
--------------------------------------------------------------------------------
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.
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:
```bash
$ rails generate scaffold post
[...]
invoke scaffold_controller
create app/controllers/posts_controller.rb
invoke erb
create app/views/posts
create app/views/posts/index.html.erb
create app/views/posts/edit.html.erb
create app/views/posts/show.html.erb
create app/views/posts/new.html.erb
create app/views/posts/_form.html.erb
[...]
```
There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
For example, the index controller action of the `posts_controller.rb` will use the `index.html.erb` view file in the `app/views/posts` directory.
The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Later on this guide you can find a more detailed documentation of each one of this three components.
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:
```bash
$ gem install actionpack
$ gem install rack
```
Now we'll create a simple "Hello World" application that uses the `titleize` method provided by Active Support.
**hello_world.rb:**
```ruby
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
```
We can see this all come together by starting up the application and then visiting `http://localhost:4567/`
```bash
$ ruby hello_world.rb
```
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:
```bash
$ gem install actionpack
$ gem install sinatra
```
Now we'll create the same "Hello World" application in Sinatra.
**hello_world.rb:**
```ruby
require 'action_view'
require 'sinatra'
get '/' do
erb 'hello world'.titleize
end
```
Then, we can run the application:
```bash
$ ruby hello_world.rb
```
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.
Templates, Partials and Layouts
-------------------------------
As mentioned before, the final HTML output is a composition of three Rails elements: `Templates`, `Partials` and `Layouts`.
Find below a brief overview of each one of them.
### Templates
Action View templates can be written in several ways. If the template file has a `.erb` extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a `.builder` extension then a fresh instance of `Builder::XmlMarkup` library is used.
Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension.
#### ERB
Within an ERB template Ruby code can be included using both `<% %>` and `<%= %>` tags. The `<% %>` are used to execute Ruby code that does not return anything, such as conditions, loops or blocks, and the `<%= %>` tags are used when you want output.
Consider the following loop for names:
```html+erb
Names of all the people
<% @people.each do |person| %>
Name: <%= person.name %>
<% end %>
```
The loop is setup in regular embedding tags `<% %>` and the name is written using the output embedding tag `<%= %>`. Note that this is not just a usage suggestion, for Regular output functions like print or puts won't work with ERB templates. So this would be wrong:
```html+erb
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
```
To suppress leading and trailing whitespaces, you can use `<%-` `-%>` interchangeably with `<%` and `%>`.
#### Builder
Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named `xml` is automatically made available to templates with a `.builder` extension.
Here are some basic examples:
```ruby
xml.em("emphasized")
xml.em { xml.b("emph & bold") }
xml.a("A Link", "href"=>"http://rubyonrails.org")
xml.target("name"=>"compile", "option"=>"fast")
```
will produce
```html
emphasized
emph & bold
A link
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" %> ``` Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page. #### The :as and :object options By default `ActionView::Partials::PartialRenderer` has its object in a local variable with the same name as the template. So, given ```erb <%= render :partial => "product" %> ``` within product we'll get `@product` in the local variable `product`, as if we had written: ```erb <%= render :partial => "product", :locals => { :product => @product } %> ``` With the `:as` option we can specify a different name for said local variable. For example, if we wanted it to be `item` instead of product+ we'd do: ```erb <%= render :partial => "product", :as => 'item' %> ``` The `:object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere, in a different ivar or in a local variable for instance. For example, instead of: ```erb <%= render :partial => "product", :locals => { :product => @item } %> ``` you'd do: ```erb <%= render :partial => "product", :object => @item %> ``` The `:object` and `:as` options can be used together. #### Rendering Collections The example of partial use describes a familiar pattern where a template needs to iterate over an array and render a sub template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial by the same name as the elements contained within. So the three-lined example for rendering all the products can be rewritten with a single line: ```erb <%= render :partial => "product", :collection => @products %> ``` When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product` , and within the `_product` partial, you can refer to `product` to get the instance that is being rendered. You can use a shorthand syntax for rendering collections. Assuming @products is a collection of `Product` instances, you can simply write the following to produce the same result: ```erb <%= render @products %> ``` Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection. #### Spacer Templates You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option: ```erb <%= render @products, :spacer_template => "product_ruler" %> ``` Rails will render the `_product_ruler` partial (with no data passed in to it) between each pair of `_product` partials. ### Layouts TODO... Using Templates, Partials and Layouts in "The Rails Way" -------------------------------------------------------- TODO... 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!') ``` In the `show` template, we'll render the `post` partial wrapped in the `box` layout: **posts/show.html.erb** ```erb <%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %> ``` The `box` layout simply wraps the `post` partial in a `div`: **posts/_box.html.erb** ```html+erb<%= post.body %>
<% end %> ``` This example would output the following: ```htmlPartial 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. View Paths ---------- TODO... 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. ### 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). #### 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" ``` #### 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" ``` #### 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") ``` ```html ``` Typically, `form_for` is used instead of `form` because it doesn't automatically include all of the model's attributes. #### 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") # => ``` ### RecordTagHelper This module provides methods for generating container tags, such as `div`, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use. #### content_tag_for Renders a container tag that relates to your Active Record Object. For example, given `@post` is the object of `Post` class, you can do: ```html+erb <%= content_tag_for(:tr, @post) do %>
```
#### 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 `vendor/assets/javascripts`.
```ruby
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
```
#### 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 `vendor/assets/stylesheets`.
```ruby
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
```
#### 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"}) # =>
```
#### image_path
Computes the path to an image asset in the `app/assets/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") # => /assets/edit.png
```
Fingerprint will be added to the filename if config.assets.digest is set to true.
```ruby
image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
```
#### image_url
Computes the url to an image asset in the `app/asset/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
```ruby
image_url("edit.png") # => http://www.example.com/assets/edit.png
```
#### image_tag
Returns an html image tag for the source. The source can be a full path or a file that exists in your `app/assets/images` directory.
```ruby
image_tag("icon.png") # => Welcome! The date and time is <%= Time.now %>
<% end %> ``` The captured variable can then be used anywhere else. ```html+erbWelcome! The date and time is <%= Time.now %>
``` **app/views/posts/special.html.erb** ```html+erbThis is a special page.
<% content_for :special_script do %> <% end %> ``` ### DateHelper #### 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") ``` #### 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") ``` #### 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, :include_seconds => true) # => less than 20 seconds ``` #### 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() ``` #### 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() ``` #### 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) ``` #### 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) ``` #### 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) ``` #### 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) ``` #### 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) ``` #### 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) ``` #### 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) ``` #### 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 ``` #### 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") ``` ### 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) ``` ```html--- first: 1 second: two third: - 1 - 2 - 3``` ### 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: ```html+erb # 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: ```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"}} ``` The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller. #### 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") # => # ``` #### 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: ```html+erb <%= 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 %> ``` #### file_field Returns a file upload input tag tailored for accessing a specified attribute. ```ruby file_field(:user, :avatar) # => ``` #### 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. ```html+erb <%= form_for @post do |f| %> <%= f.label :title, 'Title' %>: <%= f.text_field :title %>
<%= text_field_tag 'name' %>
<% end %> # => ``` #### 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. ```html+erb <%= form_tag { :action => "post" }, { :multipart => true } do %> <%= file_field_tag "file" %> <%= submit_tag %> <% end %> ``` Example output: ```ruby file_field_tag 'attachment' # => ``` #### form_tag Starts a form tag that points the action to an url configured with `url_for_options` just like `ActionController::Base#url_for`. ```html+erb <%= form_tag '/posts' do %>