ERB Template removing the trailing line

Harish Shetty picture Harish Shetty · Jan 8, 2011 · Viewed 24k times · Source

I have an ERB template for sending an email.

Name: <%= @user.name %>
<% if @user.phone.present? %>
Phone: <%= @user.phone %>
<% end %>
Address: <%= @user.address %>

I am trying to remove the blank line between Name and Address when Phone is empty.

Returned result

Name: John Miller 

Address: X124 Dummy Lane, Dummy City, CA

Expected result

Name: John Miller 
Address: X124 Dummy Lane, Dummy City, CA

I have tried to use <%--%> tags(to remove the trailing new line) without any success.

Name: <%= @user.name %>
<%- if @user.phone.present? -%>
Phone: <%= @user.phone %>
<%- end -%>
Address: <%= @user.address -%>

How do I work around this issue?

PS: I am on Rails 2.3.8.

Note 1

Right now, I am working around the issue using ruby hackery.

Helper Method:

def display_fields(names, user)
  names.collect do |name| 
    value = user.send(name)
    "#{name}: #{value}" unless value.blank?
  end.compact.join("\n")
end

View code

<%= display_fields(["Name", "Phone", "Address"], @user) %>

But this looks quite clunky to me. I am interested in knowing if anybody has been able to get the <%--%> working in ERB view templates.

Answer

willmcneilly picture willmcneilly · Nov 26, 2012

To enable trim mode you have to instantiate the ERB object with '-' as the third parameter

ERB.new(template, nil, '-')