diff --git a/sinatra-contrib/lib/sinatra/content_for.rb b/sinatra-contrib/lib/sinatra/content_for.rb index aeaeb5b5..3bb7b254 100644 --- a/sinatra-contrib/lib/sinatra/content_for.rb +++ b/sinatra-contrib/lib/sinatra/content_for.rb @@ -27,6 +27,15 @@ module Sinatra # # layout.erb # <%= yield_content :some_key %> # + # If you have provided +yield_content+ with a block and no content for the + # specified key is found, it will render the results of the block provided + # to yield_content. + # + # # layout.erb + # <%= yield_content :some_key_with_no_content do %> + # ... + # <% end %> + # # === Classic Application # # To use the helpers in a classic application all you need to do is require @@ -111,6 +120,7 @@ module Sinatra # Would pass 1 and 2 to all the blocks registered # for :head. def yield_content(key, *args) + return yield(*args) if block_given? && content_blocks[key.to_sym].empty? content_blocks[key.to_sym].map { |b| capture(*args, &b) }.join end diff --git a/sinatra-contrib/spec/content_for_spec.rb b/sinatra-contrib/spec/content_for_spec.rb index d70e625d..756e63a5 100644 --- a/sinatra-contrib/spec/content_for_spec.rb +++ b/sinatra-contrib/spec/content_for_spec.rb @@ -32,6 +32,11 @@ describe Sinatra::ContentFor do yield_content(:foo).should be_empty end + it 'renders default content if no block matches the key and a default block is specified' do + content_for(:bar) { "bar" } + yield_content(:foo) { "foo" }.should == "foo" + end + it 'renders multiple blocks with the same key' do content_for(:foo) { "foo" } content_for(:foo) { "bar" } @@ -84,6 +89,11 @@ describe Sinatra::ContentFor do yield_content(:foo).should be_empty end + it 'renders default content if no block matches the key and a default block is specified' do + render inner, :different_key + yield_content(:foo) { "foo" }.should == "foo" + end + it 'renders multiple blocks with the same key' do render inner, :multiple_blocks yield_content(:foo).gsub(/\s/, '').should == "foobarbaz"