How to render a text file without changing its formatting?

Currently I am using

<%= File.read('/path/to/file.txt') %>

to render my file on the screen, but this puts the whole file in one
line. How would I output the file on the screen the way it is saved in
the .txt document? (I can't use render_file)

Currently I am using

<%= File.read('/path/to/file.txt') %>

to render my file on the screen, but this puts the whole file in one
line. How would I output the file on the screen the way it is saved in
the .txt document? (I can't use render_file)

If the txt file has HTML formatting in it (saved as html code), then a browser will render it the way you might expect it to. But browsers don't have any particular rules for plain text, and will run them out in a single line if that's all that is there. You might try running it through the simple_format view helper to see if that fixes things for you. That will at lease put a br at the end of each single line break and a p at every double-line-break. It's not going to render other tags, like lists or similar.

Walter

Uh, well -- sure they do: collapse adjacent instances of white-space
(including tabs and newlines) to single space chars :slight_smile:

But which, to the OP's point, won't be done if the content is wrapped
in a PRE element...

Hassan Schroeder wrote in post #1070306:

Hassan Schroeder wrote in post #1070306:

lalalalala pqpqpqpqpq wrote in post #1070310:

But which, to the OP's point, won't be done if the content is wrapped
in a PRE element...

nevermind, this worked. thanks a lot.

Keep in mind that, unless you have complete control over the content of
that text file, this solution could be very dangerous from a security
perspective. For instance if you're getting that file from an end user
through some sort of file upload you better make sure you sanitize it
before sending it back to the browser to be rendered.

That's what we would call "user provided data" and you should never
trust user provided data.

Will html not automatically be escaped (assuming this is on Rails 3)
as the string will not be marked html safe? If not on 3 then
certainly it must be sanitised.

Colin

Colin Law wrote in post #1070313: