5

I'm fairly new to Sinatra, and I'm trying to access data from a database from within a partial.

Here's an example of a partial that I want on a page:

<% @articles.each do |article| %>
    <ul>
        <li> <%= article.articleName %> </li>
    </ul>
<% end %>

It works fine if I just set up a route like

get '/articles' do
     @article = Articles.all
     erb :articles
end

and the /articles page with something like

<% @articles.each do |article| %>
    <article>
        <p> <%= article.articleName %> </p>
        <p> <%= article.articleBody %> </p>
    </article>
<% end %>

However, it doesn't seem like the above code works if I put it into a partial.

Any help would be appreciated. I'm sure I'm missing something simple.

shanemcd
  • 538
  • 6
  • 14
  • I guess it's worth adding that when I run the app with the code in the partial, I get "undefined method `each' for nil:NilClass" – shanemcd Oct 19 '11 at 03:50
  • More [info here...](http://stackoverflow.com/questions/3974878/rendering-a-partial-from-a-haml-file/3975168#3975168) Phrogz's answer is better then mine :) – kfl62 Oct 19 '11 at 08:07

2 Answers2

5

Sinatra does not have built-in partials like Rails, but you can use ordinary templates as partials, as mentioned in: http://www.sinatrarb.com/faq.html#partials

Example:

articles template:

<% @articles.each do |article| %>

<%= erb :'partials/_article', :layout => false, :locals => { :article => article } %>

<% end %>

partials/_article template:

Title <%= article.title %>

...

PS: set a path to partial from template root dir. This weird syntax :'partials/_article' is a Sinatra trick, it enables you to access template in subdir, this wouldn't work (I think): :partials/_article or 'partials/_article'.

Lukas Stejskal
  • 2,542
  • 19
  • 30
2

Sinatra has no partial functionality built-in. So you have two options:

  1. build your own partial handler like here or
  2. use the partials.rb from here
ben
  • 1,819
  • 15
  • 25