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?
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?
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:
%ul
%li Home
%li Users
%li Roles
= yield(:menu)
- content_for :menu do
%li Add User
%li Change permissions
- 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.