-
Notifications
You must be signed in to change notification settings - Fork 3
Layouts and rendering.textile
h2. 레일스 레이아웃과 구성하기
이 안내서에서는 액션 컨트롤러와 액션 퓨의 기본적인 레이아웃 특징을 다룹니다. 이 안내서를 참조하면 다음과 같은 것을 할 수 있습니다.
- 레일스에 내장된 다양한 레이아웃 구성 메소드 사용하기
- 다중 컨텐츠 섹션으로 레이아웃 만들기
- 뷰에서 반복 코딩작업을 줄이기 위해 "파셜(partials)" 이용하기
- 중첩 레이아웃(하부 템플릿) 이용하기
endprologue.
h3. 개요 : 조각들을 맞물리기
이 안내서는 모델-뷰-컨트롤러 삼각관계에서 컨트롤러와 뷰 사이의 상호동작에 초점을 맞추어 설명합니다. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
h3. Creating Responses
From the controller's point of view, there are three ways to create an HTTP response:
- Call +render+ to create a full response to send back to the browser
- Call +redirect_to+ to send an HTTP redirect status code to the browser
- Call +head+ to create a response consisting solely of HTTP headers to send back to the browser
I'll cover each of these methods in turn. But first, a few words about the very easiest thing that the controller can do to create a response: nothing at all.
h4. Rendering by Default: Convention Over Configuration in Action
You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your +BooksController+ class:
class BooksController < ApplicationController endAnd the following in your routes file:
resources :booksAnd you have a view file +app/views/books/index.html.erb+:
Rails will automatically render +app/views/books/index.html.erb+ when you navigate to +/books+ and you will see "Books are coming soon!" on your screen.
However a coming soon screen is only minimally useful, so you will soon create your +Book+ model and add the index action to +BooksController+:
class BooksController < ApplicationController def index @books = Book.all end endNote that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the +action_name.html.erb+ template in the controller's view path and render it. So in this case, Rails will render the +app/views/books/index.html.erb+ file.
If we want to display the properties of all the books in our view, we can do so with an ERB template like this:
<% @books.each do |book| %>
<% end %>Title | Summary | |||
---|---|---|---|---|
<%= book.title %> | <%= book.content %> | <%= link_to 'Show', book %> | <%= link_to 'Edit', edit_book_path(book) %> | <%= link_to 'Remove', book, :confirm => 'Are you sure?', :method => :delete %> |
<%= link_to 'New book', new_book_path %>
NOTE: The actual rendering is done by subclasses of +ActionView::TemplateHandlers+. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. In Rails 2, the standard extensions are +.erb+ for ERB (HTML with embedded Ruby), +.rjs+ for RJS (JavaScript with embedded ruby) and +.builder+ for Builder (XML generator).
h4. Using +render+
In most cases, the +ActionController::Base#render+ method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customise the behaviour of +render+. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
TIP: If you want to see the exact results of a call to +render+ without needing to inspect it in a browser, you can call +render_to_string+. This method takes exactly the same options as +render+, but it returns a string instead of sending a response back to the browser.
h5. Rendering Nothing
Perhaps the simplest thing you can do with +render+ is to render nothing at all:
render :nothing => trueIf you look at the response for this using cURL, you will see the following:
$ curl -i 127.0.0.1:3000/books HTTP/1.1 200 OK Connection: close Date: Sun, 24 Jan 2010 09:25:18 GMT Transfer-Encoding: chunked Content-Type: */*; charset=utf-8 X-Runtime: 0.014297 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache$
We see there is an empty response (no data after the +Cache-Control+ line), but the request was successful because Rails has set the response to 200 OK. You can set the +:status+ option on render to change this response. Rendering nothing can be useful for AJAX requests where all you want to send back to the browser is an acknowledgement that the request was completed.
TIP: You should probably be using the +head+ method, discussed later in this guide, instead of +render :nothing+. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
h5. Rendering an Action's View
If you want to render the view that corresponds to a different action within the same template, you can use +render+ with the name of the view:
def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to(@book) else render "edit" end endIf the call to +update_attributes+ fails, calling the +update+ action in this controller will render the +edit.html.erb+ template belonging to the same controller.
If you prefer, you can use a symbol instead of a string to specify the action to render:
def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to(@book) else render :edit end endTo be explicit, you can use +render+ with the +:action+ option (though this is no longer necessary in Rails 3.0):
def update @book = Book.find(params[:id]) if @book.update_attributes(params[:book]) redirect_to(@book) else render :action => "edit" end endWARNING: Using +render+ with +:action+ is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller. Any instance variables that you require in the view must be set up in the current action before calling +render+.
h5. Rendering an Action's Template from Another Controller
What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with +render+, which accepts the full path (relative to +app/views+) of the template to render. For example, if you're running code in an +AdminProductsController+ that lives in +app/controllers/admin+, you can render the results of an action to a template in +app/views/products+ this way:
render 'products/show'Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the +:template+ option (which was required on Rails 2.2 and earlier):
render :template => 'products/show'h5. Rendering an Arbitrary File
The +render+ method can also use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications):
render "/u/apps/warehouse_app/current/app/views/products/show"Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the +:file+ option (which was required on Rails 2.2 and earlier):
render :file => "/u/apps/warehouse_app/current/app/views/products/show"The +:file+ option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
NOTE: By default, the file is rendered without using the current layout. If you want Rails to put the file into the current layout, you need to add the +:layout => true+ option.
TIP: If you're running Rails on Microsoft Windows, you should use the +:file+ option to render a file, because Windows filenames do not have the same format as Unix filenames.
h5. Wrapping it up
The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the +edit.html.erb+ template in the +views/books+ directory:
render :edit render :action => :edit render 'edit' render 'edit.html.erb' render :action => 'edit' render :action => 'edit.html.erb' render 'books/edit' render 'books/edit.html.erb' render :template => 'books/edit' render :template => 'books/edit.html.erb' render '/path/to/rails/app/views/books/edit' render '/path/to/rails/app/views/books/edit.html.erb' render :file => '/path/to/rails/app/views/books/edit' render :file => '/path/to/rails/app/views/books/edit.html.erb'Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.
h5. Using +render+ with +:inline+
The +render+ method can do without a view completely, if you're willing to use the +:inline+ option to supply ERB as part of the method call. This is perfectly valid:
render :inline => "<% products.each do |p| %><%= p.name %>
<% end %>"WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
By default, inline rendering uses ERB. You can force it to use Builder instead with the +:type+ option:
render :inline => "xml.p {'Horrid coding practice!'}", :type => :builderh5. Using +render+ with +:update+
You can also render JavaScript-based page updates inline using the +:update+ option to +render+:
render :update do |page| page.replace_html 'warning', "Invalid options supplied" endWARNING: Placing JavaScript updates in your controller may seem to streamline small updates, but it defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. We recommend using a separate RJS template instead, no matter how small the update.
h5. Rendering Text
You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+:
render :text => "OK"TIP: Rendering pure text is most useful when you're responding to AJAX or web service requests that are expecting something other than proper HTML.
NOTE: By default, if you use the +:text+ option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the +:layout => true+ option.
h5. Rendering JSON
JSON is a JavaScript data format used by many AJAX libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
render :json => @productTIP: You don't need to call +to_json+ on the object that you want to render. If you use the +:json+ option, +render+ will automatically call +to_json+ for you.
h5. Rendering XML
Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
render :xml => @productTIP: You don't need to call +to_xml+ on the object that you want to render. If you use the +:xml+ option, +render+ will automatically call +to_xml+ for you.
h5. Rendering Vanilla JavaScript
Rails can render vanilla JavaScript (as an alternative to using +update+ with an +.rjs+ file):
render :js => "alert('Hello Rails');"This will send the supplied string to the browser with a MIME type of +text/javascript+.
h5. Options for +render+
Calls to the +render+ method generally accept four options:
- +:content_type+
- +:layout+
- +:status+
- +:location+
h6. The +:content_type+ Option
By default, Rails will serve the results of a rendering operation with the MIME content-type of +text/html+ (or +application/json+ if you use the +:json+ option, or +application/xml+ for the +:xml+ option.). There are times when you might like to change this, and you can do so by setting the +:content_type+ option:
render :file => filename, :content_type => 'application/rss'h6. The +:layout+ Option
With most of the options to +render+, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action:
render :layout => 'special_layout'You can also tell Rails to render with no layout at all:
render :layout => falseh6. The +:status+ Option
Rails will automatically generate a response with the correct HTTP status code (in most cases, this is +200 OK+). You can use the +:status+ option to change this:
render :status => 500 render :status => :forbiddenRails understands both numeric status codes and symbols for status codes.
h6. The +:location+ Option
You can use the +:location+ option to set the HTTP +Location+ header:
render :xml => photo, :location => photo_url(photo)h5. Finding Layouts
To find the current layout, Rails first looks for a file in +app/views/layouts+ with the same base name as the controller. For example, rendering actions from the +PhotosController+ class will use +app/views/layouts/photos.html.erb+ (or +app/views/layouts/photos.builder+). If there is no such controller-specific layout, Rails will use +app/views/layouts/application.html.erb+ or +app/views/layouts/application.builder+. If there is no +.erb+ layout, Rails will use a +.builder+ layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
h6. Specifying Layouts on a per-Controller Basis
You can override the automatic layout conventions in your controllers by using the +layout+ declaration in the controller. For example:
class ProductsController < ApplicationController layout "inventory" #... endWith this declaration, all methods within +ProductsController+ will use +app/views/layouts/inventory.html.erb+ for their layout.
To assign a specific layout for the entire application, use a declaration in your +ApplicationController+ class:
class ApplicationController < ActionController::Base layout "main" #... endWith this declaration, all views in the entire application will use +app/views/layouts/main.html.erb+ for their layout.
h6. Choosing Layouts at Runtime
You can use a symbol to defer the choice of layout until a request is processed:
class ProductsController < ApplicationController layout :products_layoutdef show @product = Product.find(params[:id]) end
private def products_layout @current_user.special? ? "special" : "products" end
end
Now, if the current user is a special user, they'll get a special layout when viewing a product. You can even use an inline method to determine the layout:
You can also decide the layout by passing a Proc object, the block you give the Proc will be given the +controller+ instance, so you can make decisions based on the current request. For example:
class ProductsController < ApplicationController layout Proc.new { |controller| controller.request.xhr? ? 'popup' : 'application' } endh6. Conditional Layouts
Layouts specified at the controller level support +:only+ and +:except+ options that take either a method name or an array of method names which correspond to method names within the controller:
class ProductsController < ApplicationController layout "product", :except => [:index, :rss] endWith this declaration, the +product+ layout would be used for everything but the +rss+ and +index+ methods.
h6. Layout Inheritance
Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:
- +application_controller.rb+
- +posts_controller.rb+
- +special_posts_controller.rb+
- +old_posts_controller.rb+
def show @post = Post.find(params[:id]) end
def index @old_posts = Post.older render :layout => "old" end
end
In this application:
- In general, views will be rendered in the +main+ layout
- +PostsController#index+ will use the +main+ layout
- +SpecialPostsController#index+ will use the +special+ layout
- +OldPostsController#show+ will use no layout at all
- +OldPostsController#index+ will use the +old+ layout
h5. Avoiding Double Render Errors
Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that +render+ works.
For example, here's some code that will trigger this error:
def show @book = Book.find(params[:id]) if @book.special? render :action => "special_show" end render :action => "regular_show" endIf [email protected]?+ evaluates to +true+, Rails will start the rendering process to dump the +@book+ variable into the +special_show+ view. But this will not stop the rest of the code in the +show+ action from running, and when Rails hits the end of the action, it will start to render the +regular_show+ view - and throw an error. The solution is simple: make sure that you have only one call to +render+ or +redirect+ in a single code path. One thing that can help is +and return+. Here's a patched version of the method:
def show @book = Book.find(params[:id]) if @book.special? render :action => "special_show" and return end render :action => "regular_show" endMake sure you use +and return+ and not +&& return+ because while the former will work, the latter will not due to operator precedence in the Ruby Language.
Note that the implicit render done by ActionController detects if +render+ has been called, and thus avoids this error. Therefore, the following will work without errors:
def show @book = Book.find(params[:id]) if @book.special? render :action => "special_show" end endThis will render a book with +special?+ set with the +special_show+ template, while other books will render with the default +show+ template.
h4. Using +redirect_to+
Another way to handle returning responses to an HTTP request is with +redirect_to+. As you've seen, +render+ tells Rails which view (or other asset) to use in constructing a response. The +redirect_to+ method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
redirect_to photos_pathYou can use +redirect_to+ with any arguments that you could use with +link_to+ or +url_for+. In addition, there's a special redirect that sends the user back to the page they just came from:
redirect_to :backh5. Getting a Different Redirect Status Code
Rails uses HTTP status code 302 (temporary redirect) when you call +redirect_to+. If you'd like to use a different status code (perhaps 301, permanent redirect), you can do so by using the +:status+ option:
redirect_to photos_path, :status => 301Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations.
h5. The Difference Between +render+ and +redirect_to+
Sometimes inexperienced developers conceive of +redirect_to+ as a sort of +goto+ command, moving execution from one place to another in your Rails code. This is not correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
Consider these actions to see the difference:
def index @books = Book.all enddef show @book = Book.find_by_id(params[:id]) if @book.nil? render :action => "index" end end
With the code in this form, there will likely be a problem if the +@book+ variable is +nil+. Remember, a +render :action+ doesn't run any code in the target action, so nothing will set up the +@books+ variable that the +index+ view is presumably depending on. One way to fix this is to redirect instead of rendering:
def index @books = Book.all enddef show @book = Book.find_by_id(params[:id]) if @book.nil? redirect_to :action => :index end end
With this code, the browser will make a fresh request for the index page, the code in the +index+ method will run, and all will be well.
The only downside to this code, is that it requires a round trip to the browser, the browser requested the show action with +/books/1+ and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to +/books/+, the browser complies and sends a new request back to the controller asking now for the +index+ action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
While in a small app, this added latency might not be a problem, it is something to think about when speed of response is of the essence. One way to handle this double request (though a contrived example) could be:
def index @books = Book.all enddef show @book = Book.find_by_id(params[:id]) if @book.nil? @books = Book.all render "index", :alert => 'Your book was not found!' end end
Which would detect that there are no books, populate the +@books+ instance variable with all the books in the database and then directly render the +index.html.erb+ template returning it to the browser with a flash alert message telling the user what happened.
h4. Using +head+ To Build Header-Only Responses
The +head+ method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling +render :nothing+. The +head+ method takes one parameter, which is interpreted as a hash of header names and values. For example, you can return only an error header:
head :bad_requestWhich would produce the following header:
HTTP/1.1 400 Bad Request Connection: close Date: Sun, 24 Jan 2010 12:15:53 GMT Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 X-Runtime: 0.013483 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cacheOr you can use other HTTP headers to convey additional information:
head :created, :location => photo_path(@photo)Which would produce:
HTTP/1.1 201 Created Connection: close Date: Sun, 24 Jan 2010 12:16:44 GMT Transfer-Encoding: chunked Location: /photos/1 Content-Type: text/html; charset=utf-8 X-Runtime: 0.083496 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cacheh3. Structuring Layouts
When Rails renders a view as a response, it does so by combining the view with the current layout (using the rules for finding the current layout that were covered earlier in this guide). Within a layout, you have access to three tools for combining different bits of output to form the overall response:
- Asset tags
- +yield+ and +content_for+
- Partials
h4. Asset Tags
Asset tags provide methods for generating HTML that links views to feeds, JavaScript, stylesheets, images, videos and audios. These are the six asset tags available in Rails:
- +auto_discovery_link_tag+
- +javascript_include_tag+
- +stylesheet_link_tag+
- +image_tag+
- +video_tag+
- +audio_tag+
You can use these tags in layouts or other views, although the tags other than +image_tag+ are most commonly used in the +<head>+ section of a layout.
WARNING: The asset tags do not verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
h5. Linking to Feeds with +auto_discovery_link_tag+
The +auto_discovery_link_tag+ helper builds HTML that most browsers and newsreaders can use to detect the presences of RSS or ATOM feeds. It takes the type of the link (+:rss+ or +:atom+), a hash of options that are passed through to url_for, and a hash of options for the tag:
<%= auto_discovery_link_tag(:rss, {:action => "feed"}, {:title => "RSS Feed"}) %>There are three tag options available for +auto_discovery_link_tag+:
- +:rel+ specifies the +rel+ value in the link (defaults to "alternate")
- +:type+ specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
- +:title+ specifies the title of the link
h5. Linking to JavaScript Files with +javascript_include_tag+
The +javascript_include_tag+ helper returns an HTML +script+ tag for each source provided. Rails looks in +public/javascripts+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/javascripts/main.js+:
<%= javascript_include_tag "main" %>To include +public/javascripts/main.js+ and +public/javascripts/columns.js+:
<%= javascript_include_tag "main", "columns" %>To include +public/javascripts/main.js+ and +public/photos/columns.js+:
<%= javascript_include_tag "main", "/photos/columns" %>To include +http://example.com/main.js+:
<%= javascript_include_tag "http://example.com/main.js" %>The +defaults+ option loads the Prototype and Scriptaculous libraries:
<%= javascript_include_tag :defaults %>The +all+ option loads every JavaScript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries:
<%= javascript_include_tag :all %>You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well:
<%= javascript_include_tag :all, :recursive => true %>If you're loading multiple JavaScript files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +javascript_include_tag+:
<%= javascript_include_tag "main", "columns", :cache => true %>By default, the combined file will be delivered as +javascripts/all.js+. You can specify a location for the cached asset file instead:
<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %>You can even use dynamic paths such as +cache/#{current_site}/main/display+.
h5. Linking to CSS Files with +stylesheet_link_tag+
The +stylesheet_link_tag+ helper returns an HTML +<link>+ tag for each source provided. Rails looks in +public/stylesheets+ for these files by default, but you can specify a full path relative to the document root, or a URL, if you prefer. For example, to include +public/stylesheets/main.css+:
<%= stylesheet_link_tag "main" %>To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+:
<%= stylesheet_link_tag "main", "columns" %>To include +public/stylesheets/main.css+ and +public/photos/columns.css+:
<%= stylesheet_link_tag "main", "/photos/columns" %>To include +http://example.com/main.css+:
<%= stylesheet_link_tag "http://example.com/main.css" %>By default, +stylesheet_link_tag+ creates links with +media="screen" rel="stylesheet" type="text/css"+. You can override any of these defaults by specifying an appropriate option (+:media+, +:rel+, or +:type+):
<%= stylesheet_link_tag "main_print", :media => "print" %>The +all+ option links every CSS file in +public/stylesheets+:
<%= stylesheet_link_tag :all %>You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well:
<%= stylesheet_link_tag :all, :recursive => true %>If you're loading multiple CSS files, you can create a better user experience by combining multiple files into a single download. To make this happen in production, specify +:cache => true+ in your +stylesheet_link_tag+:
<%= stylesheet_link_tag "main", "columns", :cache => true %>By default, the combined file will be delivered as +stylesheets/all.css+. You can specify a location for the cached asset file instead:
<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %>You can even use dynamic paths such as +cache/#{current_site}/main/display+.
h5. Linking to Images with +image_tag+
The +image_tag+ helper builds an HTML +<img />+ tag to the specified file. By default, files are loaded from +public/images+.
WARNING: Note that you must specify the extension of the image. Previous versions of Rails would allow you to just use the image name and would append +.png+ if no extension was given but Rails 3.0 does not.
<%= image_tag "header.png" %>You can supply a path to the image if you like:
<%= image_tag "icons/delete.gif" %>You can supply a hash of additional HTML options:
<%= image_tag "icons/delete.gif", {:height => 45} %>You can also supply an alternate image to show on mouseover:
<%= image_tag "home.gif", :onmouseover => "menu/home_highlight.gif" %>You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
<%= image_tag "home.gif" %> <%= image_tag "home.gif", :alt => "Home" %>You can also specify a special size tag, in the format "{width}x{height}":
<%= image_tag "home.gif", :size => "50x20" %>In addition to the above special tags, you can supply a final hash of standard HTML options, such as +:class+, +:id+ or +:name+:
<%= image_tag "home.gif", :alt => "Go Home", :id => "HomeImage", :class => 'nav_bar' %>h5. Linking to Videos with +video_tag+
The +video_tag+ helper builds an HTML 5 +<video>+ tag to the specified file. By default, files are loaded from +public/videos+.
<%= video_tag "movie.ogg" %>Produces
Like an +image_tag+ you can supply a path, either absolute, or relative to the +public/videos+ directory. Additionally you can specify the +:size => "#{width}x#{height}"+ option just like an +image_tag+. Video tags can also have any of the HTML options specified at the end (+id+, +class+ et al).
The video tag also supports all of the +<video>+ HTML options through the HTML options hash, including:
- +:poster => 'image_name.png'+, provides an image to put in place of the video before it starts playing.
- +:autoplay => true+, starts playing the video on page load.
- +:loop => true+, loops the video once it gets to the end.
- +:controls => true+, provides browser supplied controls for the user to interact with the video.
- +:autobuffer => true+, the video will pre load the file for the user on page load.
You can also specify multiple videos to play by passing an array of videos to the +video_tag+:
<%= video_tag ["trailer.ogg", "movie.ogg"] %>This will produce: