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?
Rails Guides describes partials this way: Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
Rails provides us great functionality for managing layouts in a web application. The layouts removes code duplication in view layer. You are able to slice all your application pages to blocks such as header, footer, sidebar, body and etc.
Ruby on Rails Views Partials Partial templates (partials) are a way of breaking the rendering process into more manageable chunks. Partials allow you to extract pieces of code from your templates to separate files and also reuse them throughout your templates.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With