Preserve newline in text area with Ruby on Rails

前端 未结 2 1747
没有蜡笔的小新
没有蜡笔的小新 2020-12-15 20:52

To practice Ruby on Rails, I am creating a blog which includes a text area (following Mackenzie Child\'s tutorial). When the text is submitted, all of the newlines are remov

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 21:05

    Newlines are actually being preserved(as \r\n), you just don't see them in your index/show views.

    In these views, call simple_format on your post.body field to replace \ns with
    s(HTML newlines):

    simple_format(post.body)
    

    From docs:

    simple_format(text, html_options = {}, options = {}) public
    
    Returns text transformed into HTML using simple formatting rules.
    Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped 
    in 

    tags. One newline (\n) is considered as a linebreak and a
    tag is appended. This method does not remove the newlines from the text.

提交回复
热议问题