不要在 rails4 中显示空白字段

Don't show empty field in rails4

<p>
  <% if @person.name %>
    <strong>Name:</strong>
    <%= @person.name %>
  <% end %>
</p>

<p>
  <% if @person.gender %>
    <strong>Gender:</strong>
    <%= @person.gender %>
  <% end %>
</p>

<p>
  <% unless @person.age.blank? %>
    <strong>Age:</strong>
    <%= @person.age %>
  <% end %>
</p>

<p>
  <% unless @person.address.blank? %>
    <strong>Address:</strong>
    <%= @person.address %>
  <% end %>
</p>

这段代码工作正常。它没有显示空白字段,但我想知道还有其他方法可以做到这一点。因为在这里我一次又一次地重复相同类型的代码。我可以使用任何停止显示空白字段的 helper 吗?

有很多方法可以做到这一点,'best' 取决于您的情况。只要标签始终与属性相同,您可以采用一种简单的部分方式:

#person/_attribute.html.erb    

<% if @person.public_send attribute != nil %>
  <strong><%= attribute.to_s.capitalize %></strong>
  <%= @person.public_send attribute %>
<% end %>

这将使您的视图看起来像这样:

<p>
  <%= render 'attribute' :attribute => :name %>
</p>

<p>
  <%= render 'attribute' :attribute => :gender %>
</p>

<p>
  <%= render 'attribute' :attribute => :age %>
</p>

<p>
  <%= render 'attribute' :attribute => :address %>
</p>

不过,我必须借此机会向您宣传 HAML - 您的代码 可能 看起来像这样!

#person/_attribute.haml

- if @person.public_send attribute != nil
  %strong= attribute.to_s.capitalize
  = @person.public_send attribute

#person/show.haml

%p= render 'attribute' :attribute => :name 
%p= render 'attribute' :attribute => :gender 
%p= render 'attribute' :attribute => :age
%p= render 'attribute' :attribute => :address