using yield and content for in a partial

Time comes in your development process when you want one partial for two action with some changes in a section of html.

In that case usually developers prefer to opt for if else or creating another partial or the whole new html template but all of them are good but not being rubyist style.

To achieve that you can use yield and content_for for example :

suppose you do have a partial _a.html.erb with some html in it

<div class='main'>
<p> this is main section</p>
<div class = 'subpart'>
<p> this is subpart </p>
</div>
<div class="block_of_code">
<%= yield :block_of_code %>
</div>
</div>

In this block of code div you want to replace it with your block of code using same partial but with different block of code.

So here I have used yield :block of code and now you can use content for rendering different block of code for different actions.

for example you do have two actions :
def a
end

def b
end
 rendering the same partial _a.html.erb with a.js.erb

<% content_for :block_of_code do %>
<p> this block of code from a action</p>
<% end %>

and from b.js.erb 

<% content_for :block_of_code do %>
<p> this block of code from b action</p>
<% end %>
 so ultimately you'll get same partial with different block of code.
 

Comments

Popular posts from this blog

Installing Wowza Streaming Engine on ubuntu

Highcharts with grouped categories

Completely Uninstall and Install Rubymine on ubuntu