Rails — Add a line break into a text area

前端 未结 11 985
南旧
南旧 2020-12-12 10:21

I got a rails app where I can input a few paragraphs of text into my model. The problem is I dont know how to input any line breaks.

I\'ve tried to add \" {ln}{/ln}

相关标签:
11条回答
  • 2020-12-12 11:12

    The answers above were good:

    • the gsub (@Ian) worked well
    • the simple_format (@Karl) was a bit over the top as @Aaron pointed out, wrapping everything in <p>

    So I tweaked as follows:

    simple_format(value, {}, wrapper_tag: 'div')
    
    0 讨论(0)
  • 2020-12-12 11:13

    If you are simply displaying your string in the view. then try it with

    < p >This is my text< / p >< br />
    
    0 讨论(0)
  • 2020-12-12 11:18

    The other answers are wrong. Text area does not render
    as line breaks, because the innerHTML value of the TEXTAREA element does not render HTML..

    You need to add the Line feed HTML entity: &#10;

    EXAMPLE:

    <textarea><%= "LINE 1&#10;LINE 2&#10;LINE 3".html_safe %></textarea>
    

    See also New line in text area - Stack Overflow

    0 讨论(0)
  • 2020-12-12 11:19

    the problem with simple_format is that it's also adding other tags like <b><i><hr><h1>...
    if you just want line breaks without other tags i suggest you build a partial (lets call it line_break):

    <% text.split("\n").each do |t| %>
      <%= t %><br>
    <% end %>
    

    then, just call it from your view:

    <%= render partial: 'line_break', locals: {text: some_text} %>
    
    0 讨论(0)
  • 2020-12-12 11:23

    What version of rails are you using?? Because the way to handle this, is different in rails 2 and 3.

    Let's say the value of the record is "foo<br />bar"

    In rails 3, if you want to evaluate the html, you could do <%=raw "foo<br />bar" %>, if you do so, you'll get a line break when you will see the view.

    In rails 2 you don't have to do that, just do <%= "foo<br />bar" %>

    Also, HTML doesn't get evaluated in a textarea anyway.

    0 讨论(0)
提交回复
热议问题