Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: calling yield in a partial template?

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?

like image 927
randombits Avatar asked Jul 13 '10 21:07

randombits


People also ask

What is the partial render in the Rails?

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.

How do you use nested layouts Rails?

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.

What are partials Ruby?

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.


1 Answers

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.

like image 62
Geoff Lanotte Avatar answered Sep 25 '22 04:09

Geoff Lanotte