Read more

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

Emanuel
December 14, 2016Software engineer at makandra GmbH

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

DON'T

<%= 'foo' if bar %>
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

"\n" if bar is false

"foo\n" if bar is true


<%= nil %>

"\n"


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

" foo"


<%= 'foo' %>

<%= 'bar' %>

"foo\n\nbar\n"

DO

Write unindented code to get the expected result.

<% if bar %>
<%= 'bar' %>
<% end %>
<%= 'foo' %>
<%= 'bar' %> 
  • Use Form Models Show archive.org snapshot 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 (<% -%>).

ERB.new("  <% %>foo").result => "  foo"
ERB.new("  <%- %>foo", nil, '-').result => "foo"

ERB.new("<% %>\nfoo\n").result => "\nfoo\n"
ERB.new("<% -%>\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

ERB

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

bar

foo
bar
Emanuel
December 14, 2016Software engineer at makandra GmbH
Posted by Emanuel to makandra dev (2016-12-14 10:55)