Rails 3: How to display properly text from “textar

2019-03-09 04:56发布

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.)

9条回答
孤傲高冷的网名
2楼-- · 2019-03-09 05:19

If someone still gets redirected here and uses Rails 4: http://apidock.com/rails/v4.0.2/ActionView/Helpers/TextHelper/simple_format

You can now specify the tag it gets wrapped in (defaults to p) like so:

simple_format(my_text, {}, wrapper_tag: "div")
# => "<div>Here is some basic text...\n<br />...with a line break.</div>"
查看更多
男人必须洒脱
3楼-- · 2019-03-09 05:19

The following helper preserves new lines as line breaks, and renders any HTML or Script (e.g Javscript) as plain text.

def with_new_lines(string)
   (h(string).gsub(/\n/, '<br/>')).html_safe
end

Use as so in views

<%= with_new_lines @object.some_text %>
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-03-09 05:29

I just used white-space: pre-line. So next line (\n) will render it.

查看更多
登录 后发表回答