Skip to content

Instantly share code, notes, and snippets.

@seanami
Created July 28, 2010 23:24
Show Gist options
  • Save seanami/496702 to your computer and use it in GitHub Desktop.
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.
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
@ginjo
Copy link

ginjo commented Nov 15, 2018

Thanks for this. It was super helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment