Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

Rails 3: How to display properly text from "textarea"?

In my Rails 3 application I use textarea to let users to write a new message in a forum.

However, when the message is displayed, all newlines look like spaces (there is no <br />). Maybe there are other mismatch examples, I don't know yet.

I wonder what is the most appropriate way to deal with this.

I guess that the text that is stored in the database is OK (I see for example that < is converted to &lt;), so the main problem is the presentation.

Are there build-in helper methods in Rails for this ?

(simple_format does something that looks similar to what I need, but it adds <p> tags which I don't want to appear.)

question from:https://stackoverflow.com/questions/5852377/rails-3-how-to-display-properly-text-from-textarea

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since simple_format does not do what you want, I'd make a simple helper method to convert newlines to <br>s:

def nl2br(s)
  s.gsub(/
/, '<br>')
end

Then in your view you can use it like this:

<%= nl2br(h(@forum_post.message)) %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...