使用相同的局部用于列表和细节视图,如何区分



所以我使用相同的部分来列出博客项目并显示完整的项目。问题是,细节视图不需要在blog-image和blog-title中包含链接。这种情况下的最佳实践是什么?

我想检查一个局部变量,它决定了细节视图是否被调用,但不知何故,我不能让这个工作:

调用:

render @post, locals: {detail: 'true'}

部分:

link_to post.title, post if not defined? detail

但是局部变量没有传递给局部变量

编辑:

好了,我现在有点远了:

#index.html.haml
= render @posts
#show.html.haml
= render @post
#post/_post.html.haml
= post_counter
编辑2:好吧,解决了…在haml中嵌套if语句需要完整的括号 ,这有点令人头疼。
#post/_post.html.haml
.blog-post
  .blog-post-image
    = (defined? post_counter) ? link_to(image_tag(post.cover_image(:large)), post) : image_tag(post.cover_image(:large))

我会这样做:

#app/views/posts/index.html.erb
<%= render "post", collection: @posts %>
#app/views/posts/show.html.erb
<%= render @post %>
#app/views/posts/_post.html.erb
<%= collection ? link_to(post.title, post) : post.title %>
<%= post.body unless collection %>

我得到了collection var从这个SO帖子:

Rails: Render collection partial:获取collection的大小

如果想跟踪集合部分的索引,还可以使用[partial_name]_counter作为本地变量。

,

根据更新后的问题:

答案是使用post_counter:

.blog-post
  .blog-post-image
    = (defined? post_counter) ? link_to(image_tag(post.cover_image(:large)), post) : image_tag(post.cover_image(:large))

这可能不是最好的方法,但是您可以将变量(局部变量)传递到模板局部变量中。(和你一样)。

你的努力是好的,但render @post是rails的魔法,将忽略局部

应该是双向的

-@post.each do |post|
  render partial "post", locals: {detail: true}

render partial "post", collection: @posts, as: post, locals: {detail: true}

检查参数散列

link_to post.title, post if params[:action] == "index"

如果你在其他地方也使用它,你可能需要检查控制器

link_to post.title, post if params[:action] == "index" && params[:controller] == "posts"

显示单篇文章:

<%= render @post %>

显示文章集合:

render partial "post", collection: @posts, as: post, locals: { detail: true }

_post部分的开头添加以下行:

<% detail ||= false %>

现在您已经初始化了detail参数。不需要defined?函数:

<% unless detail %>
  <%= link_to post.title, post %>
<% end %>

最新更新