显示部分所选控制器

时间:2013-03-26 03:24:36

标签: ruby-on-rails ruby ruby-on-rails-3.2

我想要一个代码块(购物车)在我的标题中显示在2个控制器的索引和显示页面上,但不是我的应用程序的任何其他部分。

我目前的计划是将此代码部分放入,并且:

 = render partial 'layouts/cart' if the params[:controller] == "Products" || params[:controller] == "Categories"

有更好的方法吗?我正在使用Rails 3.2

3 个答案:

答案 0 :(得分:1)

我正在使用erb,我不知道haml但想法应该只是可以转让

您可以使用content_for来解决问题。

将此代码添加到您希望购物车显示的视图文件中。

Products / show.html.erb Products / index.html.erb Categories / show.html.erb,Categories / index.html.erb (如您的问题所示)。

<% content_for :cart,  render('layouts/cart') %>

现在打电话:

<%= yield :cart %>

在您的 application.html.erb 中(或者您希望购物车出现的任何地方)。

示例

布局/应用:

<!DOCTYPE html>
<html>
  <head>
    <title>Testapp</title>
    <%= stylesheet_link_tag    "application", :media => "all" %>
    <%= javascript_include_tag "application" %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <%= yield :cart%>
    <%= yield %>
  </body>
</html>

产品/显示:

<% content_for :cart,  render('layouts/cart') %>

<p>I have content_for call so my appilication.html will dispaly cart partial</p>

产品/索引:

<p>I don't have content_for call so my appilication.html will not dispaly cart partial</p>

布局/购物车:

<h1>Here I am!</h1>
访问产品索引路径将产生:

I don't have content_for call so my appilication.html will not dispaly cart partial
访问产品展示路径将产生:

Here I am!
I have content_for call so my appilication.html will dispaly cart partial

答案 1 :(得分:0)

你在那里做的事情没有任何内在错误,但是如果你需要把它放在很多地方,那么它可能容易出错。

你可以离开

= render partial 'layouts/cart'

你想使用它并把它放在

if the params[:controller] == "Products" || params[:controller] == "Categories"
部分中的

因此您只将逻辑保留在一个地方

答案 2 :(得分:0)

您应该尝试将逻辑排除在视图之外(包括部分视图)。因此,最好的方法是将其卸载到帮助器中。

助手/ application_helper.rb

module ApplicationHelper
  def show_cart
    render 'layouts/cart' if ['Products', 'Categories'].include?(params[:controller])
  end
end
视图中的

<%= show_cart %>