How do you handle partials which have differences depending on the action which is rendering them? Here's three suggestions for this problem.
<!-- index.html.erb -->
<% for article in @articles %>
<% render :layout => 'article', :object => article do %>
<p><%=h article.description %></p>
<p><%= link_to "Read More...", article %></p>
<% end %>
<% end %>
<!-- show.html.erb -->
<% stylesheet 'article' %>
<% render :layout => 'article', :object => @article do %>
<%= simple_format(h(@article.content)) %>
<% end %>
<!-- _article.html.erb -->
<div class="article">
<h2><%= link_to_unless_current h(article.name), article %></h2>
<div class="info">
by <%= article.author %> on <%= article.created_at.to_s(:long) %>
<span class="comments">
<%= link_to pluralize(article.comments.size, 'Comment'), article %>
</span>
</div>
<div class="content">
<%= yield %>
</div>
</div>
<!-- layouts/application.html.erb -->
<%= yield(:head) %>
# application_helper.rb
def stylesheet(*args)
content_for(:head) { stylesheet_link_tag(*args) }
end
/* article.css */
.article .comments_link {
display: none;
}
本文探讨了在不同动作下渲染部分视图的方法,提出了三种建议:使用布局渲染特定内容、通过条件语句选择不同模板以及利用yield来传递动态内容。这些方法有助于解决同一部分视图在不同上下文中呈现差异的问题。
3039

被折叠的 条评论
为什么被折叠?



