如何直接从 Rails 控制器返回 HTML? [英] How to return HTML directly from a Rails controller?

查看:43
本文介绍了如何直接从 Rails 控制器返回 HTML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个模型对象有一个文本"列,其中包含网页的完整 HTML.

One of my model objects has a 'text' column that contains the full HTML of a web page.

我想编写一个控制器动作,直接从控制器返回这个 HTML,而不是像控制器上的其他动作一样通过 .erb 模板传递它.

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.

我的第一个想法是将这个动作拉到一个新的控制器中,并制作一个带有空布局的自定义 .erb 模板,模板中只有 <%= modelObject.htmlContent %> -但我想知道在 Rails 中是否有更好的方法来做到这一点.

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.

推荐答案

在你的控制器 respond_to 块中,你可以使用:

In your controller respond_to block, you can use:

render :text => @model_object.html_content

或:

render :inline => "<%= @model_object.html_content %>"

所以,例如:

def show
  @model_object = ModelObject.find(params[:id])

  respond_to do |format|
    format.html { render :text => @model_object.html_content }
  end
end

这篇关于如何直接从 Rails 控制器返回 HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆