rails respond_to和各种形式的HTML响应

Luk*_*e W 5 rest ruby-on-rails

我经常使用

respond_to do |format|
...
end
Run Code Online (Sandbox Code Playgroud)

在Rails中为我的Restful行动,但我不知道理想的解决方案是什么处理各种形式的,例如,html响应.例如,调用操作A的view1可能期望返回带有包含在UL标记中的小部件列表的html,而view2期望包含在表中的相同小部件列表.一个人如何巧妙地表达我不仅要回复html格式的响应,而且我想将它包装在表格中,或者包含在UL,OL,选项或其他一些常见的面向列表的html标签中?

mač*_*ček 3

这是基本思想:

控制器

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
Run Code Online (Sandbox Code Playgroud)

意见

<!-- 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>
Run Code Online (Sandbox Code Playgroud)

用法:

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

<%= link_to "View as list",   products_path(:mode => "list") %>
<%= link_to "View as table",  products_path(:mode => "table") %> 
Run Code Online (Sandbox Code Playgroud)

注意:您需要采取一些措施来确保用户不会尝试在 URL 中指定无效的查看模式。