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

前端 未结 9 1165
予麋鹿
予麋鹿 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:10

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

    Rails got a helper method out of the box, so you dont have to write your own method.

    From the documentation:

    simple_format(text, html_options={}, options={})

    my_text = "Here is some basic text...\n...with a line break."
    
    simple_format(my_text)
    # => "<p>Here is some basic text...\n<br />...with a line break.</p>"
    
    more_text = "We want to put a paragraph...\n\n...right there."
    
    simple_format(more_text)
    # => "<p>We want to put a paragraph...</p>\n\n<p>...right there.</p>"
    
    simple_format("Look ma! A class!", :class => 'description')
    # => "<p class='description'>Look ma! A class!</p>"
    
    0 讨论(0)
  • 2021-01-31 16:14

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

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

    You can use style="white-space: pre-wrap;" in the html tag surrounding the text. This respects any line breaks in the text.

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

    You'll need to convert the plain text of the textarea to HTML.

    At the most basic level you could run a string replacement:

     message_content.gsub! /\n/, '<br />'
    

    You could also use a special format like Markdown (Ruby library: BlueCloth) or Textile (Ruby library: RedCloth).

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

    I was using Ace code-editor in my rails app and i had problem, that whenever i update or create the code, it adds always extra TAB on every line (except first). I couldn't solve it with gsub or javascript replace.. But it accidently solved itself when i disabled layout for that template.

    So, i solved it with

    render :layout => false
    
    0 讨论(0)
提交回复
热议问题