2017-03-15 49 views
0

現在我有一個循環,其中包含我不想爲每個實例變量重複的代碼。我希望通過更改實例變量來部分重用它,以便我可以爲我定義的@featured_posts和@recommended_posts使用相同的模板。如何將實例變量傳遞給視圖部分?

我在想是這樣的:

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

一個循環,我想在部分

<% @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 %> 

我應該如何處理這個存儲的例子嗎?謝謝你的幫助!

回答

1

指定任何你想要的變量posts

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

現在遍歷posts的部分。您將在posts變量有@featured_posts現在

<% 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 %> 

對於@recommended_posts呈現相同的部分,但通過@recommended_postsposts

<%= render "posts", posts: @recommended_posts %> 
+0

作品,感謝這個! – Joshua