#99 Complex Partials
Mar 31, 2008 | 8 minutes | Views, Refactoring
How do you handle partials which have differences depending on the action which is rendering them? Here's three suggestions for this problem.
I should have mentioned, not all of the tips work best for this specific example. I would probably stop after the first tip. But I wanted to give you some more ideas for solving this problem which may work well in your situation.
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 %>
<% 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 %>
<% 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>
<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) %>
<%= yield(:head) %>
application_helper.rb
def stylesheet(*args)
content_for(:head) { stylesheet_link_tag(*args) }
end
def stylesheet(*args) content_for(:head) { stylesheet_link_tag(*args) } end
article.css
.article .comments_link {
display: none;
}
.article .comments_link { display: none; }

