diff options
Diffstat (limited to 'railties/doc/guides/actionview')
-rw-r--r-- | railties/doc/guides/actionview/helpers.markdown | 91 | ||||
-rw-r--r-- | railties/doc/guides/actionview/layouts_and_rendering.txt | 761 | ||||
-rw-r--r-- | railties/doc/guides/actionview/partials.markdown | 90 |
3 files changed, 0 insertions, 942 deletions
diff --git a/railties/doc/guides/actionview/helpers.markdown b/railties/doc/guides/actionview/helpers.markdown deleted file mode 100644 index c702e83ff9..0000000000 --- a/railties/doc/guides/actionview/helpers.markdown +++ /dev/null @@ -1,91 +0,0 @@ -Helpers -==================== - -Helper Basics ------------------------- - -Helpers allow you to encapsulate rendering tasks as reusable functions. Helpers are modules, not classes, so their methods execute in the context in which they are called. They get included in a controller (typically the ApplicationController) using the helper function, like so - - Class ApplicationController < ActionController::Base - … - helper :menu - - def … - end - end - -In this way, methods in the menu helper are made available to any view or partial in your application. These methods can accept parameters, for example controller instance variables (eg; records or record collections gathered by you current controller), items from the view or partial’s locals[] hash or items from the params[] hash. You may wish to pass your controller instance variables and items from the params[] hash to the locals hash before rendering (See the section on partials). Helper methods can also accept an executable block of code. - -It is important to remember, though, that helpers are for rendering, and that they become available once a controller method has returned, while Rails is engaged in rendering the contents generated by a controller method. This means that helper methods are not available from within the methods of your controllers. - -Helpers can accomplish a variety of tasks, from formatting a complex tag for embedding content for a browser plugin (eg; Flash), to assembling a menu of options appropriate for the current context of your application, to generating sections of forms that get assembled on-the-fly. - -Helpers are organized around rendering tasks, so it is not necessary (nor necessarily desirable) to organize them around your application’s controllers or models. In fact, one of the benefits of helpers is that they are not connected via a rendering pipeline to specific controllers, like views and partials are. They can and should handle more generalized tasks. - -Here is a very simple, pseudo-example: - - module MenuHelper - def menu(records, menu_options={}) - item_options = menu_options.merge({<some stuff>}) - items = records.collect |record| do - menu_item(record, options) - end - content_tag(“ul”, items, options) - end - - def menu_item(record, item_options={})) - action = item_options[:action] - action ||= “show” - content_tag(“li”, link_to(record.title, :action => action, item_options) - end - end - - -This helper will require that records passed into it have certain fields (notably :title). The helper could be written to use this as a default, allowing the field to be overwritten by an element of item_options. - -Look at the Rails API for examples of helpers included in Rails, eg; [`ActionView::Helpers::ActiveRecordHelper`](http://api.rubyonrails.org/classes/ActionView/Helpers/ActiveRecordHelper.html). - -Passing Blocks to Helper Methods ------------------------- - -We mentioned before that blocks can be passed to helper methods. This allows for an interesting wrinkle: a block passed to a helper method can cause it to render a partial, which can then be wrapped by the helper method’s output. This can make your helper method much more reusable. It doesn’t need to know anything about the internals about what it is rendering, it just contextualizes it for the page. You can also use the helper to modify the locals hash for the partial, based on some configuration information unique to the current controller. You could implement a flexible themes system in this way. - - -Partials vs. Helpers? ------------------------- - -In general, the choice between using a partial vs. using a helper depends on the amount of flexibility you need. If the task is more about reacting to conditions than performing actual rendering, you may likely want a helper method. If you want to be able to call it from a variety of views, again, you may want to use a helper method. You can expect to extract helper methods out of code in views and partials during refactoring. - - -Tutorial -- Calling a Helper [UNFINISHED] ------------------------- - -1. Create a Rails application using `rails helper_test` -Notice the code: - - class ApplicationController < ActionController::Base - helper :all # include all helpers, all the time -For this tutorial, we'll keep this code, but you will likely want to exert more control over loading your helpers. - -2. Configure a database of your choice for the app. - -3. Inside of the `/app/helpers/` directory, create a new file called, `menu_helper.rb`. Write this in the file: - - module MenuHelpers - def menu(records, item_proc=nil) - items = records.collect{ |record| - menu_item(record, item_proc) - } - content_tag("ul", items) - end - - def menu_item(record, item_proc=nil) - item_url = item_proc.call(record) - item_url ||= { :action => :show } - content_tag("li", link_to(record.name, item_url)) - end - end - -4. Create a scaffold for some object in your app, using `./script/generate scaffold widgets`. -5. Create a database table for your widgets, with at least the fields `name` and `id`. Create a few widgets. -6. Call the menu command twice from `index.html.erb`, once using the default action, and once supplying a Proc to generate urls.
\ No newline at end of file diff --git a/railties/doc/guides/actionview/layouts_and_rendering.txt b/railties/doc/guides/actionview/layouts_and_rendering.txt deleted file mode 100644 index 00f9dbbdd9..0000000000 --- a/railties/doc/guides/actionview/layouts_and_rendering.txt +++ /dev/null @@ -1,761 +0,0 @@ -Layouts and Rendering in Rails -============================== - -This guide covers the basic layout features of Action Controller and Action View. By referring to this guide, you will be able to: - -* Use the various rendering methods built in to Rails -* Create layouts with multiple content sections -* Use partials to DRY up your views - -== Overview: How the Pieces Fit Together - -This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. 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. - -== 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. - -=== 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 actions. For example, if you have this code in your +BooksController+ class: - -[source, ruby] -------------------------------------------------------- -def show - @book = Book.find(params[:id]) -end -------------------------------------------------------- - -Rails will automatically render +app/views/books/show.html.erb+ after running the method. In fact, if you have the default catch-all route in place (+map.connect ':controller/:action/:id'+), Rails will even render views that don't have any code at all in the controller. For example, if you have the default route in place and a request comes in for +/books/sale_list+, Rails will render +app/views/books/sale_list.html.erb+ in response. - -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). You'll also find +.rhtml+ used for ERB templates and .rxml for Builder templates, but those extensions are now formally deprecated and will be removed from a future version of Rails. - -=== 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 customize the behavior 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. - -==== Rendering Nothing - -Perhaps the simplest thing you can do with +render+ is to render nothing at all: - -[source, ruby] -------------------------------------------------------- -render :nothing => true -------------------------------------------------------- - -This will send an empty response to the browser (though it will include any status headers you set with the :status option, discussed below). - -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. - -==== Using +render+ with +:action+ - -If you want to render the view that corresponds to a different action within the same template, you can use +render+ with the +:action+ option: - -[source, ruby] -------------------------------------------------------- -def update - @book = Book.find(params[:id]) - if @book.update_attributes(params[:book]) - redirect_to(@book) - else - render :action => "edit" - end - end -end -------------------------------------------------------- - -If 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. - -WARNING: 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+. - -==== Using +render+ with +:template+ - -What if you want to render a template from an entirely different controller from the one that contains the action code? You can do that with the +:template+ option to +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: - -[source, ruby] -------------------------------------------------------- -render :template => 'products/show' -------------------------------------------------------- - -==== Using +render+ with +:file+ - -If you want to use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications), you can use the +:file+ option to +render+: - -[source, ruby] -------------------------------------------------------- -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+ option - -==== 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: - -[source, ruby] -------------------------------------------------------- -render :inline => "<% products.each do |p| %><p><%= p.name %><p><% 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: - -[source, ruby] -------------------------------------------------------- -render :inline => "xml.p {'Horrid coding practice!'}", :type => :builder -------------------------------------------------------- - -==== Using +render+ with +:update+ - -You can also render javascript-based page updates inline using the +:update+ option to +render+: - -[source, ruby] -------------------------------------------------------- -render :update do |page| - page.replace_html 'warning', "Invalid options supplied" -end -------------------------------------------------------- - -WARNING: 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. I recommend using a separate rjs template instead, no matter how small the update. - -==== Rendering Text - -You can send plain text - with no markup at all - back to the browser by using the +:text+ option to +render+: - -[source, ruby] -------------------------------------------------------- -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 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 - -==== 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: - -[source, ruby] -------------------------------------------------------- -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. - -==== Rendering XML - -Rails also has built-in support for converting objects to XML and rendering that XML back to the caller: - -[source, ruby] -------------------------------------------------------- -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. - -==== Options for +render+ - -Calls to the +render+ method generally accept four options: - -* +:content_type+ -* +:layout+ -* +:status+ -* +:location+ - -===== 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: - -[source, ruby] -------------------------------------------------------- -render :file => filename, :content_type => 'application/rss' -------------------------------------------------------- - -===== 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. 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+. - -You can use the +:layout+ option to tell Rails to use a specific file as the layout for the current action: - -[source, ruby] -------------------------------------------------------- -render :layout => 'special_layout' -------------------------------------------------------- - -You can also tell Rails to render with no layout at all: - -[source, ruby] -------------------------------------------------------- -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: - -[source, ruby] -------------------------------------------------------- -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. - -===== The +:location+ Option - -You can use the +:location+ option to set the HTTP +Location+ header: - -[source, ruby] -------------------------------------------------------- -render :xml => photo, :location => photo_url(photo) -------------------------------------------------------- - -==== 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: - -[source, ruby] -------------------------------------------------------- -def show - @book = Book.find(params[:id]) - 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: - -[source, ruby] -------------------------------------------------------- -def show - @book = Book.find(params[:id]) - if @book.special? - render :action => "special_show" and return - end -end -------------------------------------------------------- - -=== 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: - -[source, ruby] -------------------------------------------------------- -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 -------------------------------------------------------- - -==== 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: - -------------------------------------------------------- -redirect_to photos_path, :status => 301 -------------------------------------------------------- - -Just like the +:status+ option for +render+, +:status+ for +redirect_to+ accepts both numeric and symbolic header designations. - -==== 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: - -[source, ruby] -------------------------------------------------------- -def index - @books = Book.find(:all) -end - -def show - @book = Book.find(params[:id]) - 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: - -[source, ruby] -------------------------------------------------------- -def index - @books = Book.find(:all) -end - -def show - @book = Book.find(params[:id]) - 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. - -=== 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: - -[source, ruby] -------------------------------------------------------- -head :bad_request -------------------------------------------------------- - -Or you can use other HTTP headers to convey additional information: - -[source, ruby] -------------------------------------------------------- -head :created, :location => photo_path(@photo) -------------------------------------------------------- - -== Structuring Layouts - -When Rails renders a view as a response, it does so by combining the view with the current layout. 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+. You can also specify a particular layout by using the +:layout+ option to +render+. - -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 - -I'll discuss each of these in turn. - -=== 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: - -* auto_discovery_link_tag -* javascript_include_tag -* stylesheet_link_tag -* 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. - -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. - -==== 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: - -[source, ruby] -------------------------------------------------------- -<%= 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 - -==== 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+: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag "main" %> -------------------------------------------------------- - -To include +public/javascripts/main.js+ and +public/javascripts/columns.js+: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag "main", "columns" %> -------------------------------------------------------- - -To include +public/javascripts/main.js+ and +public/photos/columns.js+: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag "main", "/photos/columns" %> -------------------------------------------------------- - -To include +http://example.com/main.js+: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag "http://example.com/main.js" %> -------------------------------------------------------- - -The +defaults+ option loads the Prototype and Scriptaculous libraries: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag :defaults %> -------------------------------------------------------- - -The +all+ option loads every javascript file in +public/javascripts+, starting with the Prototype and Scriptaculous libraries: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag :all %> -------------------------------------------------------- - -You can supply the +:recursive+ option to load files in subfolders of +public/javascripts+ as well: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag :all, :recursive %> -------------------------------------------------------- - -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+: - -[source, ruby] -------------------------------------------------------- -<%= 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: - -[source, ruby] -------------------------------------------------------- -<%= javascript_include_tag "main", "columns", :cache => 'cache/main/display' %> -------------------------------------------------------- - -You can even use dynamic paths such as "cache/#{current_site}/main/display"+. - -==== 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.cs+: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag "main" %> -------------------------------------------------------- - -To include +public/stylesheets/main.css+ and +public/stylesheets/columns.css+: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag "main", "columns" %> -------------------------------------------------------- - -To include +public/stylesheets/main.css+ and +public/photos/columns.css+: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag "main", "/photos/columns" %> -------------------------------------------------------- - -To include +http://example.com/main.cs+: - -[source, ruby] -------------------------------------------------------- -<%= 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): - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag "main_print", media => "print" %> -------------------------------------------------------- - -The +all+ option links every CSS file in +public/stylesheets+: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag :all %> -------------------------------------------------------- - -You can supply the +:recursive+ option to link files in subfolders of +public/stylesheets+ as well: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag :all, :recursive %> -------------------------------------------------------- - -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+: - -[source, ruby] -------------------------------------------------------- -<%= 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: - -[source, ruby] -------------------------------------------------------- -<%= stylesheet_link_tag "main", "columns", :cache => 'cache/main/display' %> -------------------------------------------------------- - -You can even use dynamic paths such as "cache/#{current_site}/main/display"+. - -==== 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: - -[source, ruby] -------------------------------------------------------- -<%= image_tag "header" %> -------------------------------------------------------- - -You can supply a path to the image if you like: - -[source, ruby] -------------------------------------------------------- -<%= image_tag "icons/delete.gif" %> -------------------------------------------------------- - -You can supply a hash of additional HTML options: - -[source, ruby] -------------------------------------------------------- -<%= image_tag "icons/delete.gif", :height => 45 %> -------------------------------------------------------- - -There are also three special options you can use with +image_tag+: - -* +:alt+ specifies the alt text for the image (which defaults to the file name of the file, capitalized and with no extension) -* +:size+ specifies both width and height, in the format "{width}x{height}" (for example, "150x125") -* +:mouseover+ sets an alternate image to be used when the onmouseover event is fired. - -=== 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: - -[source, html] -------------------------------------------------------- -<html> - <head> - </head> - <body> - <%= yield %> - <hbody> -</html> -------------------------------------------------------- - -You can also create a layout with multiple yielding regions: - -[source, html] -------------------------------------------------------- -<html> - <head> - <%= yield :head %> - </head> - <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. - -=== 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: - -[source, html] -------------------------------------------------------- -<% content_for :head do %> - <title>A simple page</title> -<% end %> - -<p>Hello, Rails!</p> -------------------------------------------------------- - -The result of rendering this page into the supplied layout would be this HTML: - -[source, html] -------------------------------------------------------- -<html> - <head> - <title>A simple page</title> - </head> - <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. - -=== 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. - -==== Naming Partials - -To render a partial as part of a view, you use the +render+ method within the view, and include the +:partial+ option: - -[source, ruby] -------------------------------------------------------- -<%= 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: - -[source, ruby] -------------------------------------------------------- -<%= render :partial => "shared/menu" %> -------------------------------------------------------- - -That code will pull in the partial from +app/views/shared/_menu.html.erb+. - -==== 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: - -[source, html] -------------------------------------------------------- -<%= render :partial => "shared/ad_banner" %> - -<h1>Products</h1> - -<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. - -TIP: For content that is shared among all pages in your application, you can use partials directly from layouts. - -==== 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: - -[source, html] -------------------------------------------------------- -new.rhtml.erb: - -<h1>New zone</h1> -<%= error_messages_for :zone %> -<%= 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: - -<% form_for(@zone) do |f| %> - <p> - <b>Zone name</b><br /> - <%= f.text_field :name %> - </p> - <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). By default, it will look for an instance variable with the same name as the partial in the parent. You can pass an object in to this local variable via the +:object+ option: - -[source, html] -------------------------------------------------------- -<%= render :partial => "customer", :object => @new_customer %> -------------------------------------------------------- - -Within the +customer+ partial, the +@customer+ variable will refer to +@new_customer+ from the parent view. - -==== 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: - -[source, html] -------------------------------------------------------- -index.rhtml.erb: - -<h1>Products</h1> -<%= 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: - -[source, html] -------------------------------------------------------- -<%= 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. - -You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option: - -[source, html] -------------------------------------------------------- -<%= 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. - -== Changelog == - -http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket] - -* October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy] -* October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) -* September 28, 2008: First draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/railties/doc/guides/actionview/partials.markdown b/railties/doc/guides/actionview/partials.markdown deleted file mode 100644 index 2988b933bc..0000000000 --- a/railties/doc/guides/actionview/partials.markdown +++ /dev/null @@ -1,90 +0,0 @@ -A Guide to Using Partials -=============================== - -This guide elaborates on the use and function of partials in Ruby on Rails. As your Rails application grows, your view templates can start to contain a lot of duplicate view code. To manage and reduce this complexity, you can by abstract view template code into partials. Partials are reusable snippets of eRB template code stored in separate files with an underscore ('_') prefix. - -Partials can be located anywhere in the `app/views` directory. File extensions for partials work just like other template files, they bear an extension that denotes what kind of code they generate. For example, `_animal.html.erb` and `_animal.xml.erb` are valid filenames for partials. - -Partials can be inserted in eRB template code by calling the `render` method with the `:partial` option. For example: - - <%= render :partial => 'foo' %> - -This inserts the result of evaluating the template `_foo.html.erb` into the parent template file at this location. Note that `render` assumes that the partial will be in the same directory as the calling parent template and have the same file extension. Partials can be located anywhere within the `app/views` directory. To use a partial located in a different directory then it the parent, add a '/' before it: - - <%= render :partial => '/common/foo' %> - -Loads the partial file from the `app/views/common/_foo.html.erb` directory. - -Abstracting views into partials can be approached in a number of different ways, depending on the situation. Sometimes, the code that you are abstracting is a specialized view of an object or a collection of objects. Other times, you can look at partials as a reusable subroutine. We'll explore each of these approaches and when to use them as well as the syntax for calling them. - -Partials as a View Subroutine ------------------------------ - -Using the `:locals` option, you can pass a hash of values which will be treated as local variables within the partial template. - - <%= render :partial => "person", :locals => { :name => "david" } %> - -The variable `name` contains the value `"david"` within the `_person.html.erb` template. Passing variables in this way allows you to create modular, reusable template files. Note that if you want to make local variables that are optional in some use cases, you will have to set them to a sentinel value such as `nil` when they have not been passed. So, in the example above, if the `name` variable is optional in some use cases, you must set: - - <% name ||= nil -%> - -So that you can later check: - - <% if name -%> - <p>Hello, <%= name %>!</p> - <% end -%> - -Otherwise, the if statement will throw an error at runtime. - -Another thing to be aware of is that instance variables that are visible to the parent view template are visible to the partial. So you might be tempted to do this: - - <%= render :partial => "person" %> - -And then within the partial: - - <% if @name -%> - <p>Hello, <%= @name %>!</p> - <% end -%> - -The potential snag here is that if multiple templates start to rely on this partial, you will need to maintain an instance variable with the same name across all of these templates and controllers. This approach can quickly become brittle if overused. - -Partials as a View of an Object --------------------------------- - -Another way to look at partials is to view them as mini-views of a particular object or instance variable. Use the `:object` option to pass an object assigns that object to an instance variable named after the partial itself. For example: - - # Renders the partial, making @new_person available through - # the local variable 'person' - render :partial => "person", :object => @new_person - -If the instance variable `name` in the parent template matches the name of the partial, you can use a shortcut: - - render :partial => "person" - -Now the value that was in `@person` in the parent template is accessible as `person` in the partial. - -Partials as a View of a Collection ------------------------------------ - -Often it is the case that you need to display not just a single object, but a collection of objects. Rather than having to constantly nest the same partial within the same iterator code, Rails provides a syntactical shortcut using the `:collection` option: - - # Renders a collection of the same partial by making each element - # of @winners available through the local variable "person" as it - # builds the complete response. - render :partial => "person", :collection => @winners - -This calls the `_person.html.erb` partial for each person in the `@winners` collection. This also creates a local variable within the partial called `partial_counter` which contains the index of the current value. So for example: - - <%= partial_counter %>) <%= person -%> - -Where `@winners` contains three people, produces the following output: - - 1) Bill - 2) Jeff - 3) Nick - -One last detail, you can place an arbitrary snippet of code in between the objects using the `:spacer_template` option. - - # Renders the same collection of partials, but also renders the - # person_divider partial between each person partial. - render :partial => "person", :collection => @winners, :spacer_template => "person_divider" |