Reputation: 20171
I want a chunk of code(a shopping cart) to display in my header on an index and show page for 2 controllers but not for any other parts of my app.
My current plan is to put this code in a partial, and:
= render partial 'layouts/cart' if the params[:controller] == "Products" || params[:controller] == "Categories"
Is there a better way? I am using Rails 3.2
Upvotes: 0
Views: 82
Reputation: 6931
(I am using erb, I don't know haml but idea should be simply transferable)
You can use content_for to solve your problem.
Add this code to the view files you would like the cart to show up.
Products/show.html.erb Products/index.html.erb Categories/show.html.erb,Categories/index.html.erb ( as in your question).
<% content_for :cart, render('layouts/cart') %>
Now call:
<%= yield :cart %>
in your application.html.erb(or wherever you would like cart to show up).
EXAMPLE:
layouts/application:
<!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>
products/show:
<% content_for :cart, render('layouts/cart') %>
<p>I have content_for call so my appilication.html will dispaly cart partial</p>
products/index:
<p>I don't have content_for call so my appilication.html will not dispaly cart partial</p>
layouts/cart:
<h1>Here I am!</h1>
visiting products index path will produce:
I don't have content_for call so my appilication.html will not dispaly cart partial
visiting products show path will produce:
Here I am!
I have content_for call so my appilication.html will dispaly cart partial
Upvotes: 1
Reputation: 29291
You should try to keep logic out of your views (that includes partials). So, best way would be to offload that into a helper.
module ApplicationHelper
def show_cart
render 'layouts/cart' if ['Products', 'Categories'].include?(params[:controller])
end
end
<%= show_cart %>
Upvotes: 0
Reputation: 6501
There isn't anything inherently wrong with what you're doing there, but if you need to put it in lots of places it could be error prone.
You could leave the
= render partial 'layouts/cart'
where you want to use it and put
if the params[:controller] == "Products" || params[:controller] == "Categories"
in the partial so you're keeping the logic in only one place
Upvotes: 0