You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:form.text_area无法显示回车换行,simple_format使用无效

Fixing Line Breaks in Rails text_area and Display

Hey there, let's break down what's going wrong and how to fix your line break issue in Rails:

The Core Problem with Your Current Code

You're using simple_format incorrectly here — it's meant to process text content (like the value stored in your database) to convert line breaks into proper HTML <br> or <p> tags, not wrap around the entire form.text_area HTML control. Your current syntax is also invalid because you've placed simple_format outside the ERB tag, which just treats the textarea as a string instead of rendering it as an input.


Solution 1: Correctly Display Line Breaks in the Edit Form's text_area

The text_area helper automatically handles line breaks from your stored data — you don't need simple_format here at all. Just render the textarea normally, and it will show any line breaks that exist in the description field:

<!-- Description -->
<div class="field">
  <label>Description :</label>
  <div class="<%= ticket.errors[:description].empty? ? 'field' : 'field error'%>">
    <%= form.text_area :description %>
  </div>
</div>

If you still don't see line breaks here, double-check that your database is storing the raw line break characters (\n) correctly — Rails doesn't escape these by default, so unless you added custom sanitization, this should work.


Solution 2: Display Line Breaks in a Show/View Page

If you want to render the saved description with proper line breaks in a non-editable view (like a show page), that's where simple_format comes in handy. It converts newline characters into HTML line breaks/paragraphs:

<!-- In your show.html.erb or similar view -->
<div class="description-section">
  <h3>Description</h3>
  <%= simple_format(@ticket.description) %>
</div>

Why Your Original Code Failed

Your line simple_format(<%= form.text_area :description %>) is invalid ERB syntax. You're trying to wrap an HTML element (the textarea) with a text-formatting helper, which just ends up escaping the HTML and displaying it as plain text instead of rendering the input control. That's why you saw no change in line break behavior.

内容的提问来源于stack exchange,提问作者AwsmDev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:27:05