Created
July 28, 2010 23:24
-
-
Save seanami/496702 to your computer and use it in GitHub Desktop.
If you're using Sinatra with ERB and you want to write helpers that take blocks, you need a little bit of magic that other more complex frameworks provide for you (capture). Here's a really really simple example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'sinatra' | |
require 'erb' | |
helpers do | |
def buffer() | |
@_out_buf | |
end | |
def capture(buffer) | |
pos = buffer.size | |
yield | |
buffer.slice!(pos..buffer.size) | |
end | |
def my_helper(&block) | |
buffer << erb(capture(buffer, &block), :layout => :my_layout) | |
end | |
end | |
template :index do | |
<<-eos | |
<!DOCTYPE html> | |
<html> | |
<head><title>Block Helper Test</title></head> | |
<body> | |
<% my_helper do %> | |
<p>This is the content in the block.</p> | |
<% end %> | |
</body> | |
</html> | |
eos | |
end | |
template :my_layout do | |
<<-eos | |
<div class="my-container"> | |
<p>This should be above the content in the block.</p> | |
<%= yield %> | |
<p>This should be below the content in the block.</p> | |
</div> | |
eos | |
end | |
get "/" do | |
erb :index | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this. It was super helpful!