Rails checks if yield: area matches in content_for

I want to do conditional rendering at the layout level based on the actual template defined by content_for(:an__area) , any idea how to do this?

+83
yield ruby-on-rails layout
Oct 11 '08 at 8:09
source share
6 answers

@content_for_whatever deprecated. Use content_for? instead content_for? , eg:

 <% if content_for?(:whatever) %> <div><%= yield(:whatever) %></div> <% end %> 
+192
Mar 11 '10 at 22:05
source share

no need to create a helper method:

 <% if @content_for_sidebar %> <div id="sidebar"> <%= yield :sidebar %> </div> <% end %> 

then of course in your opinion:

 <% content_for :sidebar do %> ... <% end %> 

I use this all the time to conditionally jump between one column and two column layouts

+10
Mar 11 '09 at 20:36
source share

Can create an assistant:

 def content_defined?(var) content_var_name="@content_for_#{var}" !instance_variable_get(content_var_name).nil? end 

And use this in your layout:

 <% if content_defined?(:an__area) %> <h1>An area is defined: <%= yield :an__area %></h1> <% end %> 
+2
Mar 11 '09 at 20:28
source share
 <%if content_for?(:content)%> <%= yield(:content) %> <%end%> 
+2
Feb 18 '14 at 16:49
source share

Well, I will shamelessly answer myself, since no one answered, and I already found the answer :) Define this as a helper method either in application_helper.rb, or anywhere you find convenient.

  def content_defined?(symbol) content_var_name="@content_for_" + if symbol.kind_of? Symbol symbol.to_s elsif symbol.kind_of? String symbol else raise "Parameter symbol must be string or symbol" end !instance_variable_get(content_var_name).nil? end 
+1
Oct 11 '08 at 16:01
source share

I'm not sure about the performance associated with calling yield twice, but it will do it regardless of the internal implementation of yield (@content_for_xyz is deprecated) and without any additional code or helper methods:

 <% if yield :sidebar %> <div id="sidebar"> <%= yield :sidebar %> </div> <% end %> 
+1
Nov 16 '09 at 12:01
source share



All Articles