Wednesday, August 8, 2012

Make it easier to use partials with blocks in rails

The shorter version of render :partial is widely known and used. These are equivalent, but the second version is so much more succinct and readable.
<%= render :partial => 'thing_one', :locals => { :foo => '123' } %>
<%= render 'thing_one', :foo => '123' %>
To use a partial with a yield in it, (what I call a "block partial"), you can use render :layout which a. doesn't read very well, (it's a partial, not a layout clearly), and b. can't be shortened nicely the way that render :partial can. So here is block_render:
#
# A trick so you can have partials that take blocks.
# Uses render :layout.
#
# Example:
# <%= block_render 'some_partial_with_a_yield', :foo => 123 do %>
# Any erb here...
# <% end %>
#
def block_render(partial_name, locals={})
render :layout => partial_name, :locals => locals do
yield
end
end
It lets you have nice neat render calls like this:
<%= block_render 'block_thing', :foo => '123' do %>
stuff inside here
<% end %>
This is a real-life example of a block partial I like to use. Those classes are bootstrap classes for making a nice drop down menu.
<%#
#
# Locals:
# right (optional)
#
# Example usage:
# <x= block_render 'shared/more_button_menu' x>
# <li><x= link_to 'Foo, '#' x></li>
# <li><x= link_to 'Bar, '#' x></li>
# <x end x>
#
-%>
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">More <span class="caret"></span></a>
<ul class="dropdown-menu<%= " pull-right" if defined?(right) && right %>">
<%= yield %>
</ul>

No comments: