0

Right now I have a loop that contains code I do not wish to repeat for each instance variable. I wish to put this in a partial and reuse it by changing the @new_posts instance variable, so I can use the same template for @featured_posts and @recommended_posts that I have defined.

I'm thinking of something like this:

<%= render "posts", posts: @featured_posts %>

An example of a loop that I wish to store in a partial

<% @new_posts.each do |post| %>
<div class="col-sm-4">
 <div class="thumbnail">
 <img src="#">
 <div class="caption">
   <h4><%= link_to post.title, post %></h4>
   <%= post.text.truncate_words(60, omission: '...') %>
   <a href="#" class="btn btn-default btn-xs" role="button">Button</a>
   </div>
  </div>
</div>
<% end %>

How should I approach this? Thanks for your help!

1 Answer 1

1

Assign whatever variable you want to posts

<%= render "posts", posts: @featured_posts %>

And now loop over posts in the partial. You will have @featured_posts in posts variable now

<% posts.each do |post| %>
  <div class="col-sm-4">
    <div class="thumbnail">
      <img src="#">
      <div class="caption">
        <h4><%= link_to post.title, post %></h4>
        <%= post.text.truncate_words(60, omission: '...') %>
        <a href="#" class="btn btn-default btn-xs" role="button">Button</a>
      </div>
    </div>
  </div>
<% end %>

For @recommended_posts render the same partial but pass @recommended_posts to posts

<%= render "posts", posts: @recommended_posts %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.