Ahmed Nadar

November 6, 2024

Common Issues with Rails Textarea Whitespace Behaviour

While building a textarea component for RapidRails UI, I discovered an interesting Rails behaviour that affects any textarea rendering, whether in regular views or ViewComponents:

Version 1: Adds unwanted whitespace
<%= tag.textarea(...) do %>  
  <%= value %>
<% end %>

Result when value is "   Hello ":
<textarea>
    Hello
</textarea>

Version 2: Preserves exact content
<%= tag.textarea(...) do %><%= value %><% end %>

Result when value is "Hello":
<textarea>Hello</textarea>

Why?!

The behaviour stems from Rails' ActionView template handling system. Specifically, in the content_tag helper:

1. The `content_tag` helper in ActionView:
# actionview/lib/action_view/helpers/tag_helper.rb

def content_tag(name, content_or_options_with_block = nil, options = nil, &block)
  if block_given?    
    content = capture(&block)  # Captures ALL whitespace  
  end
end

The capture method preserves all whitespace within the block, including:
  • Newlines after the opening do
  • Indentation before the content
  • Newlines before the end

2. Rails' own form helper avoids this by not using blocks:
# actionview/lib/action_view/helpers/tags/text_area.rb
def render  
  content_tag("textarea", value_before_type_cast, options)
end
By passing the content directly rather than using a block, it sidesteps the whitespace preservation.

Why It matters

The whitespace preservation is critical for:
  • Character count accuracy
  • Form validation
  • Content formatting
  • User experience
  • Data consistency

Best Practices

1. Use inline ERB for textarea content:
<%= tag.textarea(...) do %><%= value %><% end %>

2. Or use Rails' direct approach:
<%= content_tag("textarea", value, options) %>

While both solution behave the same, choose what you like.

RapidRails is using content_tag approach:
  • Matches Rails' native implementation
  • No whitespace concerns at all
  • More straightforward
  • Less prone to formatting issues
  • Cleaner code

3. Document this behaviour in your components/views for future reference. 

This behaviour isn't a bug—it's how Rails templates preserve whitespace. However, textareas are special because they preserve whitespace in HTML, making them more sensitive to these template formatting issues.


📚 More reads

Ahmed Nadar

About Ahmed Nadar

Ruby on Rails enthusiast at heart. I run RapidRails agency focus on Rails development & UI stack. Maker of RapidRails UI component for Ruby on Rails.
Find me on Twitter – @ahmednadar