Rails reply_to and various forms of html responses

I often use

respond_to do |format|
...
end

in Rails for my active actions, but I don’t know what the ideal solution is for processing various forms of, say, html responses. For example, view1 invoking action A can expect to return an html with a list of widgets enclosed in the UL tag, while view2 expects the same list of widgets enclosed in a table. How can I gladly express that I not only want to return a formatted html response, but I want it to be wrapped in a table or in UL, OL, parameters, or some other general list-oriented html tag?

+5
source share
3 answers

This is the main idea:

controller

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

representation

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

Using:

, :

<%= link_to "View as list",   products_path(:mode => "list") %>
<%= link_to "View as table",  products_path(:mode => "table") %> 

.. -, URL-.

+3

, . , . -, response_to (.. Html, xml, js ..), .

0

:

 map.connect ':controller/:action/:id.:format'

, , . , , , XML.

, , iphone "xmlm" ( XML Mobile), java "xml", . .

respond_to do |format|
 format.xml{  render :xml => @people.to_xml  }
 format.xmlm { do other stuff }
end

This page will help you and contains all the necessary information for implementing this material (pay attention, in particular, to the parts of custom mime types), be sure to check out the comments: http://apidock.com/rails/v2.3.4/ActionController/MimeResponds/ InstanceMethods / respond_to

0
source

All Articles