【问题标题】:Ruby on Rails: How to render file as plain text (without any HTML)Ruby on Rails:如何将文件呈现为纯文本(没有任何 HTML)
【发布时间】:2014-02-03 11:01:42
【问题描述】:

如何在 rails 中将文件呈现为纯文本/文本(不呈现任何 HTML)?

我试过了:

render file: "path/to/file", layout: false

render file: "path/to/file", content_type: 'text/plain'

两者都有

render file: "path/to/file", layout: false, content_type: 'text/plain'

但响应中仍有一些 html。

我正在使用 rails 3.2.14 和 ruby​​ 1.9.3

提前致谢。

编辑 1:

愚蠢的我,这确实有效:

render file: "path/to/file", layout: false, content_type: 'text/plain'

我正在使用谷歌浏览器检查元素,所以出现了一个 html 标记。但是当我看到源代码时,没有 HTML 标记。

我试图渲染的文件是一个没有扩展名的定制文件,它是一个制表符分隔值,我在 d3.tsv() (D3.js) 中用作参数

感谢大家的努力。 :D

编辑 2:

在编辑 1 中,我检查了响应,确实它没有任何 html 标记。但是在 d3.tsv() (D3.js) 中使用它作为参数显然不起作用。很高兴我从JetAbe 尝试了the answer 并且它有效!所以我接受了 JetAbe 的回答。

【问题讨论】:

  • 渲染了什么? layout: false 将不应用任何布局,这意味着该文件中的内容就是您所得到的。
  • 不要编辑您的问题,而是回答它并标记为已接受。以便其他人知道它已解决并且不要浪费时间。
  • 我是新手,无法发布我自己的答案。
  • 您现在应该可以这样做了。欢迎来到堆栈溢出!如果您在此 Q 中需要任何进一步的帮助,请给我留言(通过在此处的评论中添加 @AngeloNeuschitzer 或给我写电子邮件,请参阅我的个人资料)

标签: ruby-on-rails file render plaintext


【解决方案1】:

Rails 4.1 现在为 render 方法公开了以下 API:

render :plain will set the content type to text/plain render :html will set the content type to text/html render :body will not set the content type header.

事实上,他们会是deprecating use of render: text in a future release.

【讨论】:

  • 对于未来的搜索者:在 rails 4.0.0 中,为了呈现文本,您需要编写:render text: "some text"。 :plain 不起作用。
  • @7stud 情况正好相反。 “我们将在未来的版本中弃用 render :text 的使用。所以请开始使用更精确的 :plain、:html 和 :body 选项。使用 render :text 可能会带来安全风险,因为会发送内容作为文本/html。”见:guides.rubyonrails.org/…
【解决方案2】:

我认为因为你的环境是 rails 3 你可以试试这个

send_file path_to_file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多