Rails 3: How to display properly text from “textarea”?

前端 未结 9 1156
予麋鹿
予麋鹿 2021-01-31 15:31

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 spac

相关标签:
9条回答
  • 2021-01-31 16:20

    CSS-only option

    I believe one of the easiest options is to use css white-space: pre-line;

    Other answers also mentioned using white-space, but I think it needs a little more information:

    In most cases you should probably choose pre-line over pre-wrap. View the difference here.

    It's very important to keep in mind about white-space that you should not do something like this:

    <p style="white-space: pre-line;">
      <%= your.text %>
    </p>
    

    It will produce extra spaces and line-breaks in the output. Instead, go with this:

    <p style="white-space: pre-line;"><%= your.text %></p>
    

    HTML alternative

    Another way is to wrap your text in <pre> tags. And last note on my CSS option is true here as well:

    <p>
      <pre><%= your.text %></pre>
    </p>
    

    Don't separate your text from <pre> tags with spaces or line-breaks.

    Final thoughts

    After googling this matter a little I have a feeling that html-approach is considered less clean than the css one and we should go css-way. However, html-way seems to be more browser-compatible (supports archaic browsers, but who cares):

    pre tag

    white-space

    0 讨论(0)
  • 2021-01-31 16:25

    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)) %>
    
    0 讨论(0)
  • 2021-01-31 16:26

    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>"
    
    0 讨论(0)
提交回复
热议问题