I often use
respond_to do |format|
...
end
in Rails for my Restful actions, but I don't know what the ideal solution is for handling various forms of, say, html responses. For instance, view1 that calls action A might expect back html with a list of widgets wrapped in a UL tag, while view2 expects the same list of widgets wrapped in a table. How does one Restfully express that not only do I want back an html formatted response, but I want it wrapped in a table, or in a UL, OL, options, or some other common list-oriented html tag?
This is the basic idea:
class ProductsController < ApplicationController
def index
# this will be used in the view
@mode = params[:mode] || 'list'
# respond_to is used for responding to different formats
respond_to do |format|
format.html # index.html.erb
format.js # index.js.erb
format.xml do # index.xml.erb
# custom things can go in a block like this
end
end
end
end
<!-- views/products/index.html.erb -->
<h1>Listing Products</h1>
<%= render params[:mode], :products => @products %>
<!-- views/products/_list.html.erb -->
<ul>
<% for p in products %>
<li><%= p.name %></li>
<% end %>
</ul>
<!-- views/products/_table.html.erb -->
<table>
<% for p in products %>
<tr>
<td><%= p.name %></td>
</tr>
<% end %>
</table>
You can link to other views "modes" using:
<%= link_to "View as list", products_path(:mode => "list") %>
<%= link_to "View as table", products_path(:mode => "table") %>
Note: You'll want to do something to ensure that the user doesn't attempt to specify an invalid view mode in the URL.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With