Hi --
Hi.
I am writing an application that has a lot of boolean conditional display logic, like this:
<% if user.description then %> <p class="css_class"><%= user.description %></p> <% end %>
Often the displayed content is more complex than the above, and to clean up my views I am trying to pull a lot of this sort of thing into partials.
However, the problem arises that I will frequently need to format the same information in different ways. For example, the above user description appears as a standalone item so it can logically be wrapped in a <p> tag. But it might be an inline item that should appear in a <span>, or a list item that should appear in <li> tags.
That means that the enclosing tag (and, typically, CSS class reference) need to be pulled back out into the view, like:
<li class="css_class"> <%= render :partial => "user_description" %> </li>
But this will result in empty <p> or <span> or <li> tags being rendered in the event that the conditional test (in the partial) returns false, which happens frequently. So that suggests I should put the conditional logic back in the view and remove it from the partial altogether:
<% if user.description then %> <p class="css_class"> <%= render :partial => "user_description" %> </p> <% end %>
...which sort of defeats the purpose of the partial.
Is there any recognized best practice for handling this situation? What would be handy is if the render method could take an :if parameter. Or I suppose I could write a helper that forms a wrapper tag given a tag name and class, and include the helper in lots of partials:
<%= render :partial => "user_description", :locals => { :tag_name => li, :class => "css_class" %>
But I'm open to better suggestions.
I tend to do the second-to-last way you've shown. The last way, with locals, is less appealing to me, as it has the same information but in a somewhat overly abstracted form. I don't think putting the partial in an HTML element defeats the purpose. Basically the purpose is partly to un-spaghettify the view, and partly to reuse stretches of template -- and doing it that way, you do both.
David