Refactoring the View into Partial Snippets of Views

Problem

Your view doesn contain a lot of Ruby code, but its still becoming more complicated than youd like. Youd like to refactor the view logic into separate, reusable templates.

Solution

You can refactor a view template into multiple templates called partials. One template can include another by calling the render method, first seen in Recipe 15.5.

Lets start with a more complex version of the view shown in Recipe 15.5:

	
	

My shopping list

    <% @list.each do |item| %>
  • <%= item.name %> <%= link_to Delete, {:action => delete, :id => item.id}, :post => true %>
  • <% end %>

Add a new item

<%= form_tag :action => ew %> Item: <%= text_field "product", "name" %> <%= submit_tag "Add new item" %> <%= end_form_tag %>

Heres the corresponding controller class, and a dummy ListItem class to serve as the model:

	# app/controllers/list_controller.rb
	class ListController < ActionController::Base
	 def shopping_list
	 @list = [ListItem.new(4, aspirin), ListItem.new(199, succotash)]
	 end

	 # Other actions go here: add, delete, etc.
	 # …
	end
	
	class ListItem
	 def initialize(id, name)
	 @id, @name = id, name
	 end
	end

The view has two parts: the first part lists all the items, and the second part prints a form to add a new item. An obvious first step is to split out the new item form.

We can do this by creating a partial view to print the new item form. To do this, create a new file within app/ views/list/ called _new_item_form.rhtml. The underscore in front of the filename indicates that it is a partial view, not a full-fledged view for an action called new_item_form. Heres the partial file.


	

	<%= form_tag :action => 
ew %>
	Item: <%= text_field "item", "value" %>

	<%= submit_tag "Add new item" %>
	<%= end_form_tag %>

To include a partial, call the render method from within a template. Here is the _new_item_form partial integrated into the main view. The view looks exactly the same, but the code is better organized.

	
	

My shopping list

    <% @list.each do |item| %>
  • <%= item.name %> <%= link_to Delete, {:action => delete, :id => item.id}, :post => true %>
  • <% end %>
<%= render :partial => ew_item_form %>

Even though the filename starts with an underscore, when you call the partial, you omit the underscore.

Discussion

Partial views inherit all the instance variables provided by the controller, so they have access to the same instance variables as the parent view. Thats why we didn have to change any of the form code for the _new_item_form partial.

We can create a second partial to factor out the code that prints the

  • tag for each list item. Heres _list_item.rhtml:

    	
    	
  • <%= list_item.name %> <%= link_to Delete, {:action => delete, :id => list_item.id}, :post => true %>

  • And heres the revised main view:

    	
    	

    My shopping list

      <% @list.each do |item| %> <%= render :partial => list_item, :locals => {:list_item => item} %> <% end %>
    <%= render :partial => ew_item_form %>

    Partial views do not inherit local variables from their parent view, so the item variable needs to be passed in to the partial, in a special hash called :locals. Its accessible in the partial as list_item, because thats the name it was given in the hash.

    This scenario, iterating over an Enumerable and rendering a partial for each element, is very common in web applications, so Rails provides a shortcut. We can simplify our main view even more by passing our array into render (as the :collection parameter) and having it do the iteration for us:

    	
    	

    My shopping list

      <%= render :collection => @list, :partial => list_item %>
    <%= render :partial => ew_item_form %>

    The partial is rendered once for every element in @list. Each list element is made available as the local variable list_item. In case you haven guessed, this name comes from the name of the partial itself: render automatically gives _foo.rhtml a local variable called foo.

    list_item_counter is another variable that is set automatically (again, the name mirrors the name of the template). list_item_counter is the current items index in the collection undergoing iteration. This variable can be handy if you want alternating list items to show up in different styles:

    	
    	
  • <%= list_item.name %> <% css_class = list_item_counter % 2 == 0 ? a :  %> <%= link_to Delete, {:action => delete, :id => list_item.id}, {class => css_class}, :post => true %>

  • When theres no collection present, you can pass a single object into a partial by specifying an :object argument to render. This is simpler than creating a whole hash of :locals just to pass one object. As with :collection, the object will be made available as a local variable whose name is based on the name of the partial.

    Heres an example: well send the shopping list into the new_item_form.rhtml partial, so that the new item form can print a more verbose message. Heres the change to shopping_list.rhtml:

    	<%= render :partial => 
    ew_item_form, :object => @list %>
    

    Heres the new version of _new_item_form.rhtml:

    	
    	

    Add a new item to the <%= new_item_form.size %> already in this list

    <%= form_tag :action => ew %> Item: <%= text_field "product", "name" %> <%= submit_tag "Add new item" %> <%= end_form_tag %>

    See Also

    • Recipe 15.5, "Displaying Templates with Render"


  • Strings

    Numbers

    Date and Time

    Arrays

    Hashes

    Files and Directories

    Code Blocks and Iteration

    Objects and Classes8

    Modules and Namespaces

    Reflection and Metaprogramming

    XML and HTML

    Graphics and Other File Formats

    Databases and Persistence

    Internet Services

    Web Development Ruby on Rails

    Web Services and Distributed Programming

    Testing, Debugging, Optimizing, and Documenting

    Packaging and Distributing Software

    Automating Tasks with Rake

    Multitasking and Multithreading

    User Interface

    Extending Ruby with Other Languages

    System Administration



    Ruby Cookbook
    Ruby Cookbook (Cookbooks (OReilly))
    ISBN: 0596523696
    EAN: 2147483647
    Year: N/A
    Pages: 399

    Similar book on Amazon

    Flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net