Ruby-on-Rails:帮助渲染:布局 => false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4334632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby-on-Rails: Help with render: layout => false
提问by David
I am trying to access a rails app resource from an API (it sends an Application/XML GET request) and I would like to not have to parse the XML file.
我正在尝试从 API 访问 rails 应用程序资源(它发送应用程序/XML GET 请求),但我不想解析 XML 文件。
In my resources controller I have the following:
在我的资源控制器中,我有以下内容:
def get_resource
@my_resource = Resources.new
render :xml => @my_resource
end
which produces an xml file as expected. If i replace it with:
它按预期生成一个 xml 文件。如果我将其替换为:
render :layout => false
my API reports a "template missing" error. I've also tried the following:
我的 API 报告“模板丢失”错误。我还尝试了以下方法:
render :xml => @identity, :layout => false
But the page renders anyway. What's the right way to go about this?
但无论如何页面都会呈现。解决这个问题的正确方法是什么?
回答by DanneManne
When you render :xml, it does not use a layout because it doesn't use any template either. By specifying :layout => false, you tell rails to look for a template which does not exist.
渲染 :xml 时,它不使用布局,因为它也不使用任何模板。通过指定 :layout => false,你告诉 rails 寻找一个不存在的模板。
Now, if you don't want to parse an xml file, then you have a few alternatives. Either:
现在,如果您不想解析 xml 文件,那么您有几个选择。任何一个:
render :json => @my_resource
or
或者
render :text => "My resource name is: #{@my_resource.name}" # Whatever you want
It all depends on how you want the result to look, what your API expects to receive. So if you don't find any of this helpful, give an example of how you want the response to look.
这完全取决于您希望结果的外观以及您的 API 期望收到的内容。因此,如果您发现这些内容没有任何帮助,请举例说明您希望响应的外观。
回答by tjeden
def get_resource
@my_resource = Resources.new
respond_to do |wants|
wants.xml { render :xml => @my_resource }
wants.html { render :layout => false }
end
end
Read this article: http://tokumine.wordpress.com/2009/09/13/how-does-respond_to-work-in-the-rails-controllers/
阅读这篇文章:http: //tokumine.wordpress.com/2009/09/13/how-does-respond_to-work-in-the-rails-controllers/

