繁体   English   中英

rails respond_to和各种形式的HTML响应

[英]rails respond_to and various forms of html responses

我经常使用

respond_to do |format|
...
end

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

这是基本的想法:

调节器

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中指定无效的视图模式。

我认为你在这里走错了路。 首先,视图不会调用操作,反之亦然。 其次,respond_to用于显示完全不同的格式(即html,xml,js等),而不是不同的模板。

检查默认路由的此变体:

 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

这个页面对你有帮助,并包含实现这些东西所需的所有信息(特别注意关于自定义mime类型的部分),请务必查看评论: http//apidock.com/rails/v2.3.4 / ActionController的/ MimeResponds / InstanceMethods / respond_to代码

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM