代码之家  ›  专栏  ›  技术社区  ›  Luke W

Rails响应\以及各种形式的HTML响应

  •  5
  • Luke W  · 技术社区  · 15 年前

    我经常使用

    respond_to do |format|
    ...
    end
    

    在Rails中,对于我的RESTful操作,但是我不知道处理各种形式的HTML响应的理想解决方案是什么。例如,调用操作A的view1可能期望返回HTML,其中小部件列表包装在一个ul标记中,而view2期望在一个表中包装相同的小部件列表。一个RESTfully如何表达我不仅想要一个HTML格式的响应,而且想要它包装在一个表中,或者一个ul、ol、options或其他一些常见的面向列表的HTML标记中?

    3 回复  |  直到 15 年前
        1
  •  3
  •   maček    15 年前

    这是基本思想:

    控制器

    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>
    

    用途:

    您可以使用以下方式链接到其他视图“模式”:

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

    注: 您需要做一些事情来确保用户不会试图在URL中指定无效的视图模式。

        2
  •  0
  •   Slobodan Kovacevic    15 年前

    我认为你走错了路。首先,视图并不调用动作,而是相反。其次,response_to用于显示完全不同的格式(即HTML、XML、JS等),而不是不同的模板。

        3
  •  0
  •   corprew    15 年前

    检查默认路由的这个变量:

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

    请注意,它允许您通过将格式作为扩展名传入来设置格式。例如,有时我的应用程序有多个使用者,它们需要不同的XML格式。

    例如,在一次应用中,iPhone应用程序使用“XMLM”格式(XML移动),Java用户使用“XML”,因为它与完整的序列化一起工作。这使我可以将该指示器用作顶级格式。

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

    此页面将对您有所帮助,并包含实现此功能所需的所有信息(特别是有关自定义mime类型的部分),请确保查看注释: http://apidock.com/rails/v2.3.4/ActionController/MimeResponds/InstanceMethods/respond_to