shanemcd
shanemcd

Reputation: 578

Access Sinatra variable in partial

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.

Upvotes: 5

Views: 4146

Answers (2)

Lukas Stejskal
Lukas Stejskal

Reputation: 2562

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'.

Upvotes: 5

ben
ben

Reputation: 1849

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

Upvotes: 2

Related Questions