views:

299

answers:

2

I am writing a small Sinatra-based app and would like each view to be able to insert various items into the layout, for example the page title or extra CSS/javascript references in the head.

Currently my layout (erb) looks like this (simplified):

<html>
<head>
    <title>Hard Coded Title Here</title>
    <link rel="stylesheet" ... />
</head>
<body>
    <h1>Hard Coded Title Here</h1>
    <div id="content">
        <%= yield %>
    </div>
</body>
</html>

Rather than having the title and CSS/JS references hard coded, I'd like to achieve something along these lines:

<html>
<head>
    <title><%= yield :title %></title>
    <link rel="stylesheet" ... />
    <%= yield :more_head_refs %>
</head>
<body>
    <h1><%= yield :title %></h1>
    <div id="content">
        <%= yield %>
    </div>
</body>
</html>

And be able to define the content for those blocks from within each view.

Is this possible, and if so how would I go about doing it?

+2  A: 

I came up against this issue at Railscamp recently and luckily Tim Lucas was able to point me to something he forked and worked on called sinatra-content-for. This will cover what you need.

dylanfm
Awesome, that looks like exactly what I'm looking for. Thanks.
Splash
A: 

I've found this to be the most robust solution for Rails-style 'content_for' functionality in Sinatra, especially if you're using ERB templates rather than Haml:

http://github.com/kematzy/sinatra-outputbuffer

Jeff