toolmantim / sinatra-content-for forked from foca/sinatra-content-for

Sinatra extension to use a `content_for` helper similar to Rails'

This URL has Read+Write access

name age message
file .gitignore Thu May 07 06:58:41 -0700 2009 Gemspec, Rakefile, etc [foca]
file LICENSE Wed May 06 22:58:50 -0700 2009 Initial commit [foca]
file README.md Mon Aug 10 23:06:36 -0700 2009 Fixed readme links [toolmantim]
file Rakefile Thu May 07 06:58:41 -0700 2009 Gemspec, Rakefile, etc [foca]
directory lib/ Mon Aug 10 22:59:35 -0700 2009 Remove the ability to pass values to blocks (in... [toolmantim]
file sinatra-content-for.gemspec Mon Aug 10 23:22:55 -0700 2009 Update gemspec to refer to README.md [toolmantim]
directory test/ Mon Aug 10 22:59:35 -0700 2009 Remove the ability to pass values to blocks (in... [toolmantim]
README.md

ContentFor

Small extension for the Sinatra web framework that allows you to use the following helpers in your views:

<% content_for :some_key do %>
  <chunk of="html">...</chunk>
<% end %>

<% yield_content :some_key %>

This allows you to capture blocks inside views to be rendered later in this request. For example, to populate different parts of your layout from your view.

When using this with the Haml rendering engine, you should do the following:

- content_for :some_key do
  %chunk{ :of => "html" } ...

= yield_content :some_key

Note that with ERB yield_content is called without an '=' block (<%= %>), but with Haml it uses = yield_content.

Using an '=' block in ERB will output the content twice for each block, so if you have problems with that, make sure to check for this.

Usage

If you're writing "classic" style apps, then requring sinatra/content_for should be enough. If you're writing "classy" apps, then you also need to call helpers Sinatra::ContentFor in your app definition.

And how is this useful?

For example, some of your views might need a few javascript tags and stylesheets, but you don't want to force this files in all your pages. Then you can put <% yield_content :scripts_and_styles %> on your layout, inside the tag, and each view can call content_for setting the appropriate set of tags that should be added to the layout.

How is this different from foca's version?

This code was based on foca's version, which supports passing block values to the content, which means lazy rendering of the blocks. This plays havoc with anything that assumes that views are rendered before layouts, such as setting instance variables and the fancyviews plugin.

Credits

Original code by foca, inspired on the Ruby on Rails helpers with the same name. Haml support by macodely. Modified by me (Tim Lucas) for the above reasons.