Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 596
Ben Morris Avatar asked Dec 06 '22 20:12

Ben Morris


2 Answers

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? %>
like image 134
John Beynon Avatar answered Jan 25 '23 23:01

John Beynon


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

<%= @sponsor.address2 + tag('br') if @sponsor.address2? %>
like image 29
Aaron Hinni Avatar answered Jan 25 '23 22:01

Aaron Hinni