0

I have a main page that is responsible for HTML/CSS styling, but some of the contents come from partials. A partial receives some locals or params, i.e. current_user or person, and displays information if any.

Is there a way for me to check if a partial rendered anything? My end goal is something like this:

<% if my_partial can render something %>
 <div class="css_for_something">
  <%= render(partial: 'my_partial', locals: {...} ) %>
<% else %>
  <div class="css_for_no_info">
   <%= render something else %>
<% end %>

I do not want the partials to handle styling logic; they just need to display content if any. Conversely, the main page should not know anything about the logic in the partial(s), such as checking values or querying the database.

Thank you

4

2 回答 2

2

不幸的是,Chris Peter 的解决方案在 rails 4.2.4 上对我不起作用,因为它render_to_string似乎在视图中不可用。

但是,以下工作(rails 4.2.4):

<% partial_content = render partial: 'my_partial' %>
<% if partial_content.present? %>
  <%= partial_content %>
<% else %>
  <%# rendered if partial is empty %>
<% end %>

请注意,present?检查实际上只检查渲染的内容是否为空。如果返回某些内容,例如 HTML 注释,则检查返回 false。

于 2016-06-09T18:42:13.970 回答
1

尝试将生成的值存储render_to_string在变量中:

<% partial_content = render_to_string(partial: 'my_partial', locals: {...} ).strip %>

然后你可以看看它是否包含任何内容:

<% if partial_content.present? %>
  <%= partial_content %>
<% else %>
  <div class="css_for_no_info">
    <%= render something else %>
  </div>
<% end %>
于 2013-02-10T19:52:32.160 回答