Posted almost 3 years ago. Visible to the public. Repeats.

Take care of indentation and blank lines when using .erb for plain text emails

Building plain text emails with an .erb template doesn't allow you to indent code like you normally do in HTML mails.


<%= 'foo' if bar %>

"\n" if bar is false

"foo\n" if bar is true

<%= nil %>


<% if true %> <%= 'foo' %> <% end %>

" foo"

<%= 'foo' %> <%= 'bar' %>



Write unindented code to get the expected result.

<% if bar %> <%= 'bar' %> <% end %> <%= 'foo' %> <%= 'bar' %>
  • Use Form Models to move logic out of the template.
  • Sometimes it makes sense to use .haml. It helps to write more beautiful code, but makes indentation more difficult.

Understanding trim mode for .erb

.erb has two approaches to handle leading spaces (<%- %>) and trailing newlines (<% -%>).

Copy" <% %>foo").result => " foo"" <%- %>foo", nil, '-').result => "foo""<% %>\nfoo\n").result => "\nfoo\n""<% -%>\nfoo\n", nil, '-').result => "foo\n"
  • You can combine removing leading spaces and removing trailing newlines.
  • You need to enable trim mode for erb like above: new(str, safe_level=nil, trim_mode=nil, eoutvar='_erbout')

Difference between Rails mailer and ERB

Rails mailer

<% if true %> <%= 'bar' %> <% end %> <%= 'foo' %> <%= 'bar' %>
bar foo bar


<% if true %> <%= 'bar' %> <% end %> <%= 'foo' %> <%= 'bar' %>
bar foo bar

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Emanuel De
Last edit:
about 1 year ago
by Judith Roth
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more