Ruby-on-rails 如何直接从 Rails 控制器返回 HTML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1958759/
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
How to return HTML directly from a Rails controller?
提问by Nate
One of my model objects has a 'text' column that contains the full HTML of a web page.
我的模型对象之一有一个“文本”列,其中包含网页的完整 HTML。
I'd like to write a controller action that simply returns this HTML directly from the controller rather than passing it through the .erb templates like the rest of the actions on the controller.
我想编写一个控制器动作,它直接从控制器返回这个 HTML,而不是像控制器上的其余动作一样通过 .erb 模板传递它。
My first thought was to pull this action into a new controller and make a custom .erb template with an empty layout, and just <%= modelObject.htmlContent %>in the template - but I wondered if there were a better way to do this in Rails.
我的第一个想法是将这个动作拉到一个新的控制器中,并制作一个带有空布局的自定义 .erb 模板,并且只是<%= modelObject.htmlContent %>在模板中 - 但我想知道在 Rails 中是否有更好的方法来做到这一点。
回答by Dan McNevin
In your controller respond_toblock, you can use:
在您的控制器respond_to块中,您可以使用:
render :text => @model_object.html_content
or:
或者:
render :inline => "<%= @model_object.html_content %>"
So, something like:
所以,像这样:
def show
@model_object = ModelObject.find(params[:id])
respond_to do |format|
format.html { render :text => @model_object.html_content }
end
end
回答by Vincent Woo
In latest Rails (4.1.x), at least, this is much simpler than the accepted answer:
至少在最新的 Rails (4.1.x) 中,这比公认的答案简单得多:
def show
render html: '<div>html goes here</div>'.html_safe
end
回答by Selvamani
Its works for me
它对我有用
def show
@model_object = ModelObject.find(params[:id])
respond_to do |format|
format.html { render :inline => "<%== @model_object['html'] %>" }
end
end

