Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write partial ERB template in Sinatra? [closed]

Tags:

ruby

erb

sinatra

How to refactor this code? I write on Sinatra I need to separate into a separate file

<div class="row">
  <div class="col-xs-3">
    <% @user.posts.each do |post| %>
      <a href="/posts/<%= post.id %>"><%= post.title %></a><br>
      <p><%= post.body %></p>
      <% unless post.comment.blank? %>
        <% post.comment.each do |comment| %> 
          <p><%= comment.body %></p>
          <% unless comment.comment.blank? %>
            <% comment.comment.each do |comment2| %> 
              <p><%= comment2.body %></p>
              <% unless comment2.comment.blank? %>
                <% comment2.comment.each do |comment3| %> 
                  <p><%= comment3.body %></p>
                <% end %> 
              <% end %> 
            <% end %> 
          <% end %>   
        <% end %>   
      <% end %> 
    <% end %>
  </div>
</div>

my model looped comment

def up
    create_table :comments do |t|
      t.string :body
      t.integer :post_id
      t.integer :comment_id
      t.timestamps
    end
  end

This is my migration model comment

like image 852
user3437693 Avatar asked Oct 01 '22 06:10

user3437693


1 Answers

From the documentation:

Use it as follows to render the mypartial.haml(1) or the admin/mypartial.haml(2) partials, or with a collection (3) & (4):

<%= partial(:mypartial) %> <!--(1)-->
<%= partial(:'admin/mypartial') %> <!--(2)-->
<%= partial(:object, :collection => @objects) %> <!--(3)-->
<%= partial(:'admin/object', :collection => @objects) %> <!--(4)-->

In (1) & (2), the partial will be rendered plain from their files, with no local variables (specify them with a hash passed into :locals). In (3) & (4), the partials will be rendered, populating the local variable object with each of the objects from the collection.

So your code should be:

<div class="row">
  <div class="col-xs-3">
    <% @user.posts.each do |post| %>
      <a href="/posts/<%= post.id %>"><%= post.title %></a><br>
      <p><%= post.body %></p>
      <%= partial(:comment, :collection => post.comment) %>
    <% end %>
  </div>
</div>

with the new file comment.erb:

<p><%= comment.body %></p>
<%= partial(:comment, :collection => comment.comment) %>
like image 70
Uri Agassi Avatar answered Oct 16 '22 16:10

Uri Agassi