Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ERB Template removing the trailing line

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.

like image 278
Harish Shetty Avatar asked Jan 08 '11 07:01

Harish Shetty


3 Answers

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

ERB.new(template, nil, '-')
like image 120
willmcneilly Avatar answered Nov 19 '22 06:11

willmcneilly


I had to combine the answers by willmcneilly, RobinBrouwer and fbo.

enable trim mode

ERB.new(File.read(filename), nil, '-')

Change to -%>

<% $things.each do |thing| -%>
  <object name="<%= thing.name %>">
    <type><%= thing.name %></type>
  </object>
<% end -%>

And finally, convert from dos to unix. I used the following in Vim:

:set fileformat=unix
:w
like image 38
Scymex Avatar answered Nov 19 '22 04:11

Scymex


Try this:

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

Also, don't know if this will work:

Name: <%= @user.name %>
<%= "Phone: #{@user.phone}" if @user.phone.present? -%>
Address: <%= @user.address %>

If that doesn't work either, this should do the trick:

Name: <%= @user.name %><%= "\nPhone: #{@user.phone}" if @user.phone.present? %>
Address: <%= @user.address %>
like image 5
RobinBrouwer Avatar answered Nov 19 '22 06:11

RobinBrouwer