Rails 3:如何正确显示"textarea"中的文本? [英] Rails 3: How to display properly text from "textarea"?
问题描述
在我的Rails 3应用程序中,我使用textarea
允许用户在论坛中写一条新消息.
In my Rails 3 application I use textarea
to let users to write a new message in a forum.
但是,显示消息时,所有换行符都看起来像空格(没有<br />
).也许还有其他不匹配的例子,我还不知道.
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 <
), so the main problem is the presentation.
Rails中是否有内置的辅助方法?
Are there build-in helper methods in Rails for this ?
( simple_format 所做的事情看起来与我需要的类似,但是会添加<p>
我不想出现的标签.)
(simple_format does something that looks similar to what I need, but it adds <p>
tags which I don't want to appear.)
推荐答案
由于simple_format
不能满足您的要求,因此,我将提供一个简单的帮助方法,将换行符转换为<br>
s:
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(/\n/, '<br>')
end
然后在您的视图中可以像这样使用它:
Then in your view you can use it like this:
<%= nl2br(h(@forum_post.message)) %>
这篇关于Rails 3:如何正确显示"textarea"中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!