开发者

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 pr开发者_如何学Goetty 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?


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? %>


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

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


<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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜