Rails Partial Template 的问题

jiwoorico · 2013年10月31日 · 最后由 jiwoorico 回复于 2013年10月31日 · 2052 次阅读

最近正在看 Agile Web Development with Rails,看到 partial template.里面有一段话,看不大明白:

Now that we have a partial for a line item, let’s do the same for the cart. First, we’ll create the _cart.html.erb template. This is basically our carts/show.html.erb template but using cart instead of @cart, and without the notice. (Note that it’s OK for a partial to invoke other partials.)

Download rails32/depot_j/app/views/carts/_cart.html.erb
<div class="cart_title">Your Cart</div>
<table>
➤ <%= render(cart.line_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', cart, method: :delete,
confirm: 'Are you sure?' %>

这里为什么要用 cart 替代 @cart? 谢谢

调用这个 partial 的时候用了 :cart => @cart 了吧

局部模板里面会有一个文件名同名的局部变量,对应这个模板就是 cart。

这个变量可以显式传进去,也可以隐式传进去

<!-- 显式 -->
<%= render :partial => 'cart', :object => @cart %>
<!-- :object 的值转成局部变量 cart -->

<!-- 隐式 -->
<%= render @cart %>
<%= render :cart %> <!-- 这个好像会自动找 @cart,没有会报错,没测试过 -->

在局部模板调用实例变量也行的,转成局部变量会比较解藕吧。

局部模板还有一种用法,是直接传一个集合

<%= render :partial => 'cart', :collection => @carts %>

<!-- 等同于,但效率有差别,上面的效率高 -->
<% @carts.each do |cart| %>
  <%= render cart %>
<% end %>

这时候外部并没有 @cart 这个实例,而是将 @carts 每个元素传进去,所以局部模板内部用 cart 局部变量就很自然了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号