Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Tree: 612fea185a
Fetching contributors…

Cannot retrieve contributors at this time

518 lines (346 sloc) 18.138 kB

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.

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

TODO…

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 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:

gem install actionpack
gem install rack

Now we’ll create a simple “Hello World” application that uses the titleize method provided by Action View.

hello_world.rb:

require ‘rubygems’
require ‘action_view’
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/

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 in the same way.

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

gem install actionpack
gem install sinatra

Now we’ll create the same “Hello World” application in Sinatra.

hello_world.rb:

require ‘rubygems’
require ‘action_view’
require ‘sinatra’

get ‘/’ do
erb ‘hello world’.titleize
end

Then, we can run the application:

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

TODO…

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

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:

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

<%= render :partial => ‘post’, :layout => ‘box’, :locals => {:post => @post} %>

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

posts/_box.html.erb

<%= yield %>

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

<% div_for(post) do >

<= post.body >


< end %>

This example would output the following:

Partial Layouts are cool!

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

<% render(:layout => ‘box’, :locals => {:post => @post}) do >
< div_for(post) do >

<= 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

Active Record Helper

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.

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”

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”

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”)

Title


Body


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”:

input(“post”, “title”) # =>

Asset Tag Helper

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:

ActionController::Base.asset_host = “assets.example.com”
image_tag(“rails.png”) # => Rails

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 # =>


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.

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 # =>


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”}) # =>

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

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”) # => Icon

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” # =>

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.

javascript_include_tag :defaults

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

javascript_include_tag :all

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).

javascript_include_tag :all, :cache => true # =>

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

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

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

Atom Feed Helper

atom_feed

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

config/routes.rb

map.resources :posts

app/controllers/posts_controller.rb

def index
@posts = Post.find(: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))

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

Benchmark Helper

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.

Cache Helper

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 :partial => “shared/footer” >
< end %>

Capture Helper

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! <%= @greeting %>

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

Welcome! <%= yield :special_script %>

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 %>

TODO continue at http://ap.rubyonrails.org/ on ActionView::Helpers::DateHelper

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:

before_filter :set_expert_locale

def set_expert_locale
I18n.locale = :expert if current_user.expert?
end

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.

Changelog

Lighthouse Ticket

Jump to Line
Something went wrong with that request. Please try again.