From 39e1ac658efc80e4c54abef4f1c7679e4b3dc2ac Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 18 Jan 2009 18:10:58 +0000 Subject: Merge docrails --- .../doc/guides/html/layouts_and_rendering.html | 944 +++++++++------------ 1 file changed, 408 insertions(+), 536 deletions(-) (limited to 'railties/doc/guides/html/layouts_and_rendering.html') diff --git a/railties/doc/guides/html/layouts_and_rendering.html b/railties/doc/guides/html/layouts_and_rendering.html index 30c114ef82..037714db78 100644 --- a/railties/doc/guides/html/layouts_and_rendering.html +++ b/railties/doc/guides/html/layouts_and_rendering.html @@ -1,246 +1,80 @@ - - Layouts and Rendering in Rails - - - - - + + Layouts and Rendering in Rails + + + + - +

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.

+
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, if you use the :file option, 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 optionBy 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 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.

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

+

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><%= p.name %><p><% end %>"
-
+
render :inline => "<% products.each do |p| %><p><%= p.name %><p><% end %>"
@@ -403,16 +288,15 @@ http://www.gnu.org/software/src-highlite --> 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:

+

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 => :builder
-
+
render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder

2.2.6. Using render with :update

-

You can also render javascript-based page updates inline using the :update option to render:

+

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"
-end
-
+end
@@ -431,20 +314,19 @@ http://www.gnu.org/software/src-highlite -->

2.2.7. Rendering Text

-

You can send plain text - with no markup at all - back to the browser by using the :text option to render:

+

You can send plain text - with no markup at all - back to the browser by using the :text option to render:

-
render :text => "OK"
-
+
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.Rendering pure text is most useful when you’re responding to AJAX or web service requests that are expecting something other than proper HTML.
@@ -452,56 +334,53 @@ http://www.gnu.org/software/src-highlite --> Note -By default, if you use the :text option, the file 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 +By default, if you use the :text option, the file 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

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

+

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 => @product
-
+
render :json => @product
- +
Tip 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.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.

2.2.9. Rendering XML

-

Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:

+

Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:

-
render :xml => @product
-
+
render :xml => @product
- +
Tip 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.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.

2.2.10. Rendering Vanilla JavaScript

-

Rails can render vanilla JavaScript (as an alternative to using update with n .rjs file):

+

Rails can render vanilla JavaScript (as an alternative to using update with n .rjs file):

-
render :js => "alert('Hello Rails');"
-
-

This will send the supplied string to the browser with a MIME type of text/javascript.

+
render :js => "alert('Hello Rails');"
+

This will send the supplied string to the browser with a MIME type of text/javascript.

2.2.11. Options for render

-

Calls to the render method generally accept four options:

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

+

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 => 'special_layout'
+

You can also tell Rails to render with no layout at all:

-
render :layout => false
-
+
render :layout => false
The :status Option
-

Rails will automatically generate a response with the correct HTML status code (in most cases, this is 200 OK). You can use the :status option to change this:

+

Rails will automatically generate a response with the correct HTML status code (in most cases, this is 200 OK). You can use the :status option to change this:

render :status => 500
-render :status => :forbidden
-
-

Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in actionpack/lib/action_controller/status_codes.rb. You can also see there how it maps symbols to status codes in that file.

+render :status => :forbidden +

Rails understands either numeric status codes or symbols for status codes. You can find its list of status codes in actionpack/lib/action_controller/status_codes.rb. You can also see there how it maps symbols to status codes in that file.

The :location Option
-

You can use the :location option to set the HTTP Location header:

+

You can use the :location option to set the HTTP Location header:

-
render :xml => photo, :location => photo_url(photo)
-
+
render :xml => photo, :location => photo_url(photo)

2.2.12. 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. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. 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.

+

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. If there is no such controller-specific layout, Rails will use /app/views/layouts/application.html.erb. 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.

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:

+

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"
   #...
-end
-
-

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

+end +

With 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"
   #...
-end
-
-

With this declaration, all views in the entire application will use app/views/layouts/main.html.erb for their layout.

+end +

With this declaration, all views in the entire application will use app/views/layouts/main.html.erb for their layout.

Choosing Layouts at Runtime
-

You can use a symbol to defer the choice of layout until a request is processed:

+

You can use a symbol to defer the choice of layout until a request is processed:

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

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

class ProductsController < ApplicationController
   layout proc{ |controller| controller.
   # ...
-end
-
+end
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:

+

Layouts specified at the controller level support :only and :except options that take either a method name or an array of method names:

class ProductsController < ApplicationController
@@ -639,10 +509,10 @@ http://www.gnu.org/software/src-highlite -->
   #...
 end
-

With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.

+

With those declarations, the inventory layout would be used only for the index method, the product layout would be used for everything else except the rss method, and the rss method will have its layout determined by the automatic layout rules.

Layout Inheritance
-

Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:

-

application_controller.rb:

+

Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example:

+

application_controller.rb:

class ApplicationController < ActionController::Base
   layout "main"
   #...
-end
-
-

posts_controller.rb:

+end +

posts_controller.rb:

class PostsController < ApplicationController
   # ...
-end
-
-

special_posts_controller.rb:

+end +

special_posts_controller.rb:

class SpecialPostsController < PostsController
   layout "special"
   # ...
-end
-
-

old_posts_controller.rb:

+end +

old_posts_controller.rb:

render :layout => "old" end # ... -end -
-

In this application:

-
+

In this application:

+

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

+

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:

if @book.special? render :action => "special_show" end -end -
-

If @book.special? 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 show view - and throw an error. The solution is simple: make sure that you only have 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:

+end +

If @book.special? 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 show view - and throw an error. The solution is simple: make sure that you only have 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:

if @book.special? render :action => "special_show" and return end -end -
+end

2.3. Using redirect_to

-

Another way to handle returning responses to a 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:

+

Another way to handle returning responses to a 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_path
-
-

You 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 photos_path
+

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

2.3.1. Getting a Different Redirect Status Code

-

Rails uses HTTP status code 302 (permanent redirect) when you call redirect_to. If you'd like to use a different status code (perhaps 301, temporary redirect), you can do so by using the :status option:

+

Rails uses HTTP status code 302 (permanent redirect) when you call redirect_to. If you’d like to use a different status code (perhaps 301, temporary redirect), you can do so by using the :status option:

redirect_to photos_path, :status => 301
-

Just like the :status option for render, :status for redirect_to accepts both numeric and symbolic header designations.

+

Just like the :status option for render, :status for redirect_to accepts both numeric and symbolic header designations.

2.3.2. The Difference Between render and redirect

-

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 a HTTP 302 status code.

-

Consider these actions to see the difference:

+

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 a HTTP 302 status code.

+

Consider these actions to see the difference:

if @book.nil? render :action => "index" and return end -end -
-

With the code in this form, there will be 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:

+end +

With the code in this form, there will be 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:

if @book.nil? redirect_to :action => "index" and return 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.

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

2.4. Using head To Build Header-Only Responses

-

The head method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling render :nothing. The head method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:

+

The head method exists to let you send back responses to the browser that have only headers. It provides a more obvious alternative to calling render :nothing. The head method takes one response, which is interpreted as a hash of header names and values. For example, you can return only an error header:

-
head :bad_request
-
-

Or you can use other HTTP headers to convey additional information:

+
head :bad_request
+

Or you can use other HTTP headers to convey additional information:

-
head :created, :location => photo_path(@photo)
-
+
head :created, :location => photo_path(@photo)

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

-
    +

    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 @@ -846,10 +705,10 @@ Partials

    -

    I'll discuss each of these in turn.

    +

    I’ll discuss each of these in turn.

    3.1. Asset Tags

    -

    Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:

    -
      +

      Asset tags provide methods for generating HTML that links views to assets like images, javascript, stylesheets, and feeds. There are four types of include tag:

      +
      • auto_discovery_link_tag @@ -871,26 +730,25 @@ image_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.

      +

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

      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:

      +

      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:

      -
        +
        <%= 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") @@ -908,180 +766,159 @@ http://www.gnu.org/software/src-highlite -->

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

    +

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

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", "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 "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 "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 :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 %>
+

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 :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 => 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' %>
-
-

+
<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %>
+

-

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

+

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

-
<%= stylesheet_link_tag "main" %>
-
-

To include public/stylesheets/main.css and public/stylesheets/columns.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", "columns" %>
+

To include public/stylesheets/main.css and public/photos/columns.css:

-
<%= stylesheet_link_tag "main", "/photos/columns" %>
-
-

To include http://example.com/main.cs:

+
<%= stylesheet_link_tag "main", "/photos/columns" %>
+

To include http://example.com/main.cs:

-
<%= stylesheet_link_tag "http://example.com/main.cs" %>
-
-

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 "http://example.com/main.cs" %>
+

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

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 :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 => 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' %>
-
-

+
<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %>
+

3.1.4. Linking to Images with image_tag

-

The image_tag helper builds an HTML <image> tag to the specified file. By default, files are loaded from public/images. If you don't specify an extension, .png is assumed by default:

+

The image_tag helper builds an HTML <image> tag to the specified file. By default, files are loaded from public/images. If you don’t specify an extension, .png is assumed by default:

-
<%= image_tag "header" %>
-
-

You can supply a path to the image if you like:

+
<%= image_tag "header" %>
+

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

You can supply a hash of additional HTML options:

-
<%= image_tag "icons/delete.gif", :height => 45 %>
-
-

There are also three special options you can use with image_tag:

-
+

There are also three special options you can use with image_tag:

+

3.2. Understanding yield

-

Within the context of a layout, yield identifies a section where content from the view should be inserted. The simplest way to use this is to have a single yield, into which the entire contents of the view currently being rendered is inserted:

+

Within the context of a layout, yield identifies a section where content from the view should be inserted. The simplest way to use this is to have a single yield, into which the entire contents of the view currently being rendered is inserted:

<body> <%= yield %> <hbody> -</html> -
-

You can also create a layout with multiple yielding regions:

+</html> +

You can also create a layout with multiple yielding regions:

<body> <%= yield %> <hbody> -</html> -
-

The main body of the view will always render into the unnamed yield. To render content into a named yield, you use the content_for method.

+</html> +

The main body of the view will always render into the unnamed yield. To render content into a named yield, you use the content_for method.

3.3. Using content_for

-

The content_for method allows you to insert content into a yield block in your layout. You only use content_for to insert content in named yields. For example, this view would work with the layout that you just saw:

+

The content_for method allows you to insert content into a yield block in your layout. You only use content_for to insert content in named yields. For example, this view would work with the layout that you just saw:

<title>A simple page</title> <% end %> -<p>Hello, Rails!</p> -
-

The result of rendering this page into the supplied layout would be this HTML:

+<p>Hello, Rails!</p> +

The result of rendering this page into the supplied layout would be this HTML:

<body> <p>Hello, Rails!</p> <hbody> -</html> -
-

The content_for method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise-generic layout.

+</html> +

The content_for method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It’s also useful for inserting tags that load page-specific javascript or css files into the header of an otherwise-generic layout.

3.4. Using Partials

-

Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

+

Partial templates - usually just called "partials" - are another device for breaking apart the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.

3.4.1. Naming Partials

-

To render a partial as part of a view, you use the render method within the view, and include the :partial option:

+

To render a partial as part of a view, you use the render method within the view, and include the :partial option:

-
<%= render :partial => "menu" %>
-
-

This will render a file named _menu.html.erb at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:

+
<%= render :partial => "menu" %>
+

This will render a file named _menu.html.erb at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you’re pulling in a partial from another folder:

-
<%= render :partial => "shared/menu" %>
-
-

That code will pull in the partial from app/views/shared/_menu.html.erb.

+
<%= render :partial => "shared/menu" %>
+

That code will pull in the partial from app/views/shared/_menu.html.erb.

3.4.2. Using Partials to Simplify Views

-

One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:

+

One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what’s going on more easily. For example, you might have a view that looked like this:

<p>Here are a few of our fine products:</p> ... -<%= render :partial => "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.

+<%= render :partial => "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.

@@ -1203,18 +1033,17 @@ http://www.gnu.org/software/src-highlite -->

3.4.3. Partial Layouts

-

A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:

+

A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:

-
<%= render :partial => "link_area", :layout => "graybar" %>
-
-

This would look for a partial named _link_area.html.erb and render it using the layout _graybar.html.erb. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master layouts folder).

+
<%= render :partial => "link_area", :layout => "graybar" %>
+

This would look for a partial named _link_area.html.erb and render it using the layout _graybar.html.erb. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master layouts folder).

3.4.4. Passing Local Variables

-

You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:

-

new.html.erb:

+

You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:

+

new.html.erb:

<h1>New zone</h1>
 <%= error_messages_for :zone %>
-<%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %>
-
-

edit.html.erb:

+<%= render :partial => "form", :locals => { :button_label => "Create zone", :zone => @zone } %> +

edit.html.erb:

<h1>Editing zone</h1>
 <%= error_messages_for :zone %>
-<%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %>
-
-

_form.html.erb:

+<%= render :partial => "form", :locals => { :button_label => "Update zone", :zone => @zone } %> +

_form.html.erb:

<p> <%= f.submit button_label %> </p> -<% end %> -
-

Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.

-

Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:

+<% end %> +

Although the same partial will be rendered into both views, the label on the submit button is controlled by a local variable passed into the partial.

+

Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:

-
<%= render :partial => "customer", :object => @new_customer %>
-
-

Within the customer partial, the @customer variable will refer to @new_customer from the parent view.

+
<%= render :partial => "customer", :object => @new_customer %>
+

Within the customer partial, the @customer variable will refer to @new_customer from the parent view.

@@ -1268,110 +1093,157 @@ http://www.gnu.org/software/src-highlite --> In previous versions of Rails, the default local variable would look for an instance variable with the same name as the partial in the parent. This behavior is deprecated in Rails 2.2 and will be removed in a future version.
-

If you have an instance of a model to render into a partial, you can use a shorthand syntax:

+

If you have an instance of a model to render into a partial, you can use a shorthand syntax:

-
<%= render :partial => @customer %>
-
-

Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it.

+
<%= render :partial => @customer %>
+

Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it.

3.4.5. Rendering Collections

-

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

-

index.html.erb:

+

Partials are very useful in rendering collections. When you pass a collection to a partial via the :collection option, the partial will be inserted once for each member in the collection:

+

index.html.erb:

<h1>Products</h1>
-<%= render :partial => "product", :collection => @products %>
-
-

_product.html.erb:

+<%= render :partial => "product", :collection => @products %> +

_product.html.erb:

-
<p>Product Name: <%= product.name %></p>
-
-

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. To use a custom local variable name within the partial, specify the :as option in the call to the partial:

+
<p>Product Name: <%= product.name %></p>
+

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. To use a custom local variable name within the partial, specify the :as option in the call to the partial:

-
<%= render :partial => "product", :collection => @products, :as => :item %>
-
-

With this change, you can access an instance of the @products collection as the item local variable within the partial.

+
<%= render :partial => "product", :collection => @products, :as => :item %>
+

With this change, you can access an instance of the @products collection as the item local variable within the partial.

- +
Tip Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by _counter. For example, if you're rendering @products, within the partial you can refer to product_counter to tell you how many times the partial has been rendered.Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by _counter. For example, if you’re rendering @products, within the partial you can refer to product_counter to tell you how many times the partial has been rendered.
-

You can also specify a second partial to be rendered between instances of the main partial by using the :spacer_template option:

+

You can also specify a second partial to be rendered between instances of the main partial by using the :spacer_template option:

-
<%= render :partial => "product", :collection => @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.

-

There's also a shorthand syntax available for rendering collections. For example, if @products is a collection of products, you can render the collection this way:

-

index.html.erb:

+
<%= render :partial => "product", :collection => @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.

+

There’s also a shorthand syntax available for rendering collections. For example, if @products is a collection of products, you can render the collection this way:

+

index.html.erb:

<h1>Products</h1>
-<%= render :partial => @products %>
-
-

_product.html.erb:

+<%= render :partial => @products %> +

_product.html.erb:

-
<p>Product Name: <%= product.name %></p>
-
-

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:

-

index.html.erb:

+
<p>Product Name: <%= product.name %></p>
+

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:

+

index.html.erb:

<h1>Contacts</h1>
-<%= render :partial => [customer1, employee1, customer2, employee2] %>
-
-

_customer.html.erb:

+<%= render :partial => [customer1, employee1, customer2, employee2] %> +

_customer.html.erb:

-
<p>Name: <%= customer.name %></p>
-
-

_employee.html.erb:

+
<p>Name: <%= customer.name %></p>
+

_employee.html.erb:

-
<p>Name: <%= employee.name %></p>
-
-

In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.

+
<p>Name: <%= employee.name %></p>
+

In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.

+

3.5. Using Nested Layouts

+

You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here’s an example:

+

Suppose you have the follow ApplicationController layout:

+

app/views/layouts/application.erb

+
+
+
<html>
+<head>
+  <title><%= @page_title %><title>
+  <% stylesheet_tag 'layout' %>
+  <style type="text/css"><%= yield :stylesheets %></style>
+<head>
+<body>
+  <div id="top_menu">Top menu items here</div>
+  <div id="menu">Menu items here</div>
+  <div id="main"><%= yield %></div>
+</body>
+</html>
+

On pages generated by NewsController, you want to hide the top menu and add a right menu:

+

app/views/layouts/news.erb

+
+
+
<% content_for :stylesheets do %>
+  #top_menu {display: none}
+  #right_menu {float: right; background-color: yellow; color: black}
+<% end -%>
+<% content_for :main %>
+  <div id="right_menu">Right menu items here</div>
+  <%= yield %>
+  <% end -%>
+<% render :file => 'layouts/application' %>
+
+ + + +
+Note +In versions of Rails before Rails 2.3, you should use render 'layouts/applications' instead of render :file => 'layouts/applications\'
+
+

That’s it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.

+

There are several ways of getting similar results with differents sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the ActionView::render method via render 'layouts/news\' to base a new layout on the News layout.

4. Changelog

- -
    + +
      +
    • +

      +December 27, 2008: Merge patch from Rodrigo Rosenfeld Rosas covering subtemplates +

      +
    • +
    • +

      +December 27, 2008: Information on new rendering defaults by Mike Gunderloy +

      +
    • November 9, 2008: Added partial collection counter by Mike Gunderloy @@ -1400,7 +1272,7 @@ September 28, 2008: First draft by Mike Gun

-
- + + -- cgit v1.2.3