Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails check if yield :area is defined in content_for

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

like image 427
William Yeung Avatar asked Oct 11 '08 08:10

William Yeung


5 Answers

@content_for_whatever is deprecated. Use content_for? instead, like this:

<% if content_for?(:whatever) %>
  <div><%= yield(:whatever) %></div>
<% end %>
like image 95
gudleik Avatar answered Nov 04 '22 06:11

gudleik


not really necessary to create a helper method:

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

then of course in your view:

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

I use this all the time to conditionally go between a one column and two column layout

like image 20
efalcao Avatar answered Nov 04 '22 05:11

efalcao


<%if content_for?(:content)%>
  <%= yield(:content) %>
<%end%>
like image 3
gregwinn Avatar answered Nov 04 '22 06:11

gregwinn


Can create a helper:

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 %>
like image 2
Nick B Avatar answered Nov 04 '22 07:11

Nick B


Ok I am going to shamelessly do a self reply as no one has answered and I have already found the answer :) Define this as a helper method either in application_helper.rb or anywhere you found 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
like image 1
William Yeung Avatar answered Nov 04 '22 07:11

William Yeung