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.
To enable trim mode you have to instantiate the ERB object with '-' as the third parameter
ERB.new(template, nil, '-')
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
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 %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With