Partial with multiple exits in rails

I am looking for a partial solution with several yields .

In a real example, I have this view structure:

Base application.erb ( /views/layouts/application.erb ):

 <!DOCTYPE html> <head> <title>Some title</title> </head> <body> <div class="page"> <%= yield %> </div> </body> </html> 

Some partial DRY my code ( /views/shared/content.erb ):

 <div class="content"> <div class="sidebar"> <%= yield :sidebar %> </div> <div class="main"> <%= yield %> </div> </div> 

And the controller view ( /views/home/index.erb ):

 <%= render :partial => 'layouts/header' %> <%= render :partial => 'shared/navigation' %> <% # It is close to what I want to do %> <%= render :layout => 'shared/content' do %> <% content_for :sidebar do %> <%# This is will go to application.erb, not in content.erb %> <%= render :partial => 'shared/menu' %> <% end %> <%= yield %> <% end %> <%= render :partial => 'layouts/footer' %> 

Thus, the main problem is to have a block of templates with many profitability areas and the ability to transmit custom html or display other partial ones.

+4
source share
2 answers

In my case, I found a solution like this.

In my controller view ( /views/home/index.erb ):

 <% sidebar_content = render :partial => 'shared/slider' %> <%= render :layout => 'shared/content', :locals => {:sidebar => sidebar_content} do %> <%= yield %> <% end %> 

Partially with several areas ( /views/shared/content.erb ):

 <div class="content"> <div class="sidebar"> <%= sidebar %> </div> <div class="main"> <%= yield %> </div> </div> 

This solution does not look very nice, but it works. I hope to find something better in the near future.

+2
source

This question is old, but it still matters when I searched the answer on Google.

I came up with a solution that is not yet beautiful, it works very well. The idea uses the Rails capture method, which takes a block and stores its contents in a variable:

controller.html.erb

 <%= render 'shared/partial', body: capture { %> My body content <% }, footer: capture { %> My footer content <% } %> 

shared /_partial.html.erb

 <div id="body"><%= body %></div> <div id="footer"><%= footer %></div> 

Hope this helps someone!

+4
source

Source: https://habr.com/ru/post/1487447/


All Articles