Reputation: 578
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
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