如何在“显示”页面以及第二个较大的部分中呈现小部分



我有一个简单的博客应用程序。

我使用部分_post.html.erb来呈现我的索引页中的帖子。

_post.html.erb有一个div class=submission_details,它与我的show行动中使用的相同。我如何将该部分偏出,以便我可以在_post.html.erb部分和show.html.erb页面中使用它?

posts_controller.rb

def index
  @posts = Post.all
end
def show
  @post = Post.find(params[:id])
end

文章/index.html.erb

<%= render @posts %>

文章/_post.html.erb

<%= post.title %>
<div class="submission_details">
  <%= time_ago_in_words(post.created_at) %>
  <span id="submission_details_<%= post.id %>">
  submitted by <%= link_to "#{post.user.name} (#{post.user.reputation_for(:points).to_i})", post.user %>
  </span>
</div>

文章/show.html.erb

<%= @post.title %>
<%= @post.content %>
<div class="submission_details">
  <%= time_ago_in_words(@post.created_at) %>
  <span id="submission_details_<%= @post.id %>">
  submitted by <%= link_to "#{@post.user.name} (#{@post.user.reputation_for(:points).to_i})", @post.user %>
  </span>
</div>

我试着做一个shared/submission_details部分如下:

共享/_submission_details.html.erb

  <%= time_ago_in_words(@post.created_at) %>
  <span id="submission_details_<%= @post.id %>">
  submitted by <%= link_to "#{@post.user.name} (#{@post.user.reputation_for(:points).to_i})", @post.user %>
  </span>

这是render 'shared/submission_details'渲染的show动作,但在index动作中给了我nil。我如何正确定义@post的index行动?

在分部中,您可以定义一个局部变量,当您呈现分部时,正确的语法应该是:

render(partial: 'post_information', locals: { post: @post }

但可以缩写为

render('post_information', post: @post)

用于show操作,对于部分_post.html而言。erb,你的post实例不是在变量@post上,而是在本地变量post上,所以你可以这样做:

render('post_information', post: post)

文章/index.html.erb

<%= render @posts %>

文章/_post.html.erb

<%= post.title %>
<div class="submission_details">
  <%= render 'post_information', post: post %>
</div>

文章/show.html.erb

<%= @post.title %>
<%= @post.content %>
<div class="submission_details">
  <%= render 'post_information', post: @post %>
</div>

文章/_post_information.html.erb

<%= time_ago_in_words(post.created_at) %>
<span id="submission_details_<%= post.id %>">
submitted by <%= link_to "#{post.user.name} (#{post.user.reputation_for(:points).to_i})", post.user %>
</span>

相关内容

最新更新