2014-01-15 55 views
6

如何在rails中呈現文件爲純文本/文本(無需呈現任何HTML)?Ruby on 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標籤。

的文件,我試圖渲染是不帶擴展定製的文件,這是一個製表符分隔值I作爲參數d3.tsv()(D3.js)使用

謝謝大家的努力。 :d

編輯2:

在編輯1,我查了反應,這是真的,它不與任何HTML標記。但是在d3.tsv()(D3.js)中使用它作爲參數顯然不起作用。很高興我嘗試了the answerJetAbe,它的工作原理!所以我接受了JetAbe的答案。

+0

什麼得到呈現? 'layout:false'將不適用佈局,這意味着文件中的內容就是你所得到的。 – sevenseacat

+0

看看這裏http://stackoverflow.com/questions/12591566/rails-3-render-plaintext-page-using-view – Abs

+0

而不是編輯你的問題,回答它並標記爲accepted.so,其他人知道它的解決了,不要浪費時間。 –

回答

4

我想是因爲你的ENV是軌道3,你可以試試這個

send_file path_to_file 
7

的Rails 4.1現在公開以下API爲render方法:

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.

+0

對於未來的搜索者:在rails 4.0.0中,爲了呈現文本需要寫:'渲染文本:「一些文本」'。 :平原不起作用。 – 7stud

+1

@ 7stud恰恰相反。 「我們將在未來的版本中不再使用render:text。所以請開始使用更精確的:plain,:html和:body選項。使用render:text可能會帶來安全風險,因爲內容是以text/html的形式發送的。「 請參閱:http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#rendering-content-from-string –

相關問題