【ror学习笔记5】局部模板
一。分离购物车视图add_to_cart.rhtml
Rails提供了一个功能:你可以将一个集合传递给负责渲染局部模板的方法,该方法就会自动多次渲染局部模板——每次都传入集合中的一个元素作为参数。
render()方法接受两个参数:局部模板的名字和一组对象的集合(局部模板文件名字前面则会加_)。局部模板内部会有一个和它的名字一样的名字的变量,值是对象集合的当前变量值。
views/store/add_to_cart.rhtml
<div class="cart-title">Your Cart </div>
<table>
<%= render(:partial =>"cart_item" , :collection => @cart.items) %>
<tr class="total-line">
<td colspan = "2">Total</td>
<td class="total-cell"><%=number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart" , :action=>:empty_cart%>
views/store/_cart_item.rhtml
<tr>
<td><%= cart_item.quantity%>×</td>
<td><%=h(cart_item.title)%></td>
<td class="item-price"><%= number_to_currency(cart_item.price) %></td>
</tr>
二。用于显示购物车的局部模板
render方法的:object参数接受一个对象作为参数,并将其赋值给一个与局部模板同名的变量
修改store.rhtml,加上16-18行
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
2 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
3
4 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5 <head>
6 <title>Pragprog Books Online Store</title>
7 <%= stylesheet_link_tag 'depot' ,:media=>"all"%>
8 </head>
9 <body id="store">
10 <div id="banner">
11 <!--<img src="/images/logo.png"/>-->
12 <%= @page_title || "Pragmatic Bookshelf"%>
13 </div>
14 <div id="columns">
15 <div id="side">
16 <div id="cart">
17 <%= render(:partial => "cart", :object => @cart) %>
18 </div>
19 <a href="http://www....">Home</a><br/>
20 <a href="http://www..../faq">Question</a><br/>
21 <a href="http://www..../news">News</a><br/>
22 <a href="http://www..../contact">Contact</a><br/>
23 </div>
24 <div id="main">
25 <% if flash[:notice] -%>
26 <div id="notice"><%=flash[:notice] %></div>
27 <% end -%>
28 <%= yield:layout%>
29 </div>
30 </div>
31 </body>
32 </html>
33
添加_cart.rhtml,它同add_to_cart.rhtml几乎一样,但是使用了cart变量而不是@cart变量。
<div class="cart-title">Your Cart </div>
<table>
<%= render(:partial =>"cart_item" , :collection => cart.items) %>
<tr class="total-line">
<td colspan = "2">Total</td>
<td class="total-cell"><%=number_to_currency(@cart.total_price) %></td>
</tr>
</table>
<%= button_to "Empty cart" , :action=>:empty_cart%>
修改store_controller.rb的add_to_cart方法,redirect_to_index方法和index方法,使浏览器重定向到首页
class StoreController < ApplicationController
def index
@products = Product.find_products_for_sale
@cart = find_cart
end
def add_to_cart
begin
@product = Product.find(params[:id])
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access invalid product #{params[:id]}")
redirect_to_index("Invalid product")
else
@cart = find_cart
@cart.add_product(@product)
redirect_to_index
end
end
def empty_cart
session[:cart] = nil
redirect_to_index("Your cart is currently empty")
end
def redirect_to_index(msg=nil)
flash[:notice] = msg if msg
redirect_to :action => :index
end
private
def find_cart
session[:cart] ||=Cart.new
end
end