panych
10/23/2013 - 1:17 PM

Block alias in Ruby on Rails

Block alias in Ruby on Rails

<article>
  <%= yield %>
</article>
<article>
  <%= body %>
</article>
<nav>
  <% items.each do |item| %>
    <a href="<%= item[:url] %>"><%= item[:text] %></a>
  <% end %>
</nav>
<!-- Usage: -->
<!-- home/index.html.erb -->
<%= b 'nav', :items => @nav_items %>

<%= b 'article' do %>
  <h1>Title</h1>
  <p>lorem</p>
<% end %>

<!-- old style -->
<%= render :partial => 'nav', :locals => { :items => @nav_items } %>

<%= render :layout => 'article_old' do %>
  <h1>Title</h1>
  <p>lorem</p>
<% end %>
# application_helper.rb
def b(block_name, options={}, &block)
  options.merge!(:body => capture(&block)) if block_given?
  render :partial => block_name, :locals => options
end