Ben Morris
Ben Morris

Reputation: 377

Rails: What is the best way to only display a line when not empty in html.erb?

PART 1: The below code seems to work fine, but there must be a better way to do the second line. This is to display a user address. It is pretty simple, where if there is content for the second line of an address, I output that and a line break.

      <%= @sponsor.address1 %><br />
      <%= raw "#{@sponsor.address2} <br />" unless @sponsor.address2.empty? %>
      <%= @sponsor.city %>, <%= @sponsor.state %> <%= @sponsor.zip %>

Is there some obvious, more elegant way to do this?

PART 2: What if the value may also be nil? Should I handle that in the model? Is there some simple way to have a model return blank instead of nil?

Nesting this in yet another condition seems too messy. Can someone tell me the best rails way to accomplish part 1 and/or 2 above?

Upvotes: 4

Views: 2296

Answers (3)

Aaron Hinni
Aaron Hinni

Reputation: 14716

Instead of dealing with raw, you can use the tag helper for the <br/>

<%= @sponsor.address2 + tag('br') if @sponsor.address2? %>

Upvotes: 4

John Beynon
John Beynon

Reputation: 37507

Few more options if you want to make the div conditional too;

<%= content_tag :div do -%>
  @sponsor.address2
<% end if @sponsor.address2? -%>

or

<%= content_tag :div, @sponsor.address2 if @sponsor.address2? %>

Upvotes: 8

bassneck
bassneck

Reputation: 4043

<div>
  <%= @sponsor.address1 %>
</div>
<div>
  <%= @sponsor.address2 if @sponsor.address2? %>
</div>

This should handle both nil? and empty? cases.

You can style divs if you wan't to. By default the should render above each other. If address2? returs false, there will be just an empty div of 0px height that cannot be seen.

Upvotes: 3

Related Questions