views:

50

answers:

1

I see this sometimes in a partial erb template:

<%= yield :someval %>

Other times there is no yield at all.

What's the advantage of calling yield in a partial?

+4  A: 

I have used it in the past if I have a partial that could be called from different pages that might need some contextual content from the page.

A use case that I had was for a menu. I had my stock menu items, but then I had a yield(:menu), so that what the user loaded the administration page, I could add menu items from the page instead of writing a condition statement in the partial itself.

This is some pseudo code:

_menu.haml

%ul
  %li Home
  %li Users
  %li Roles
  = yield(:menu)

users.haml

- content_for :menu do
  %li Add User
  %li Change permissions

roles.haml

- content_for :menu do
  %li Add Role

As opposed to:

%ul
  %li Home
  %li Users
  %li Roles
  - if current_controller == 'users'
    %li Add User
    %li Change permissions
  - if current_controller == 'roles'
    %li Add Role

While both are functional (if it was real code), I prefer the first method. The second can spiral out of control and get pretty ugly pretty fast. It is a matter of preference though.

Geoff Lanotte