2013-10-29 21 views
1

我正在开发一个Web应用程序,它必须在主页上显示产品列表。 为此,我有一个ProductsController的:如何为使用HAML的视图创建助手?

 class ProductsController < ApplicationController 
     include ProductsHelper 
     def index 
     @products = Product.last(6).reverse 
     end 
    end 

和相应的视图index.haml:

.main-container.col3-layout 
     .main 
     .col-wrapper 
      .col-main 
      .box.best-selling 
       %h3 Latest Products 
       %table{:border => "0", :cellspacing => "0"} 
       %tbody 
        - @products.each_slice(2) do |slice| 
        %tr 
         - slice.each do |product| 
         %td 
          %a{:href => product_path(:id => product.id)} 
          = product.title 
          %img.product-img{:alt => "", :src => product.image.path + product.image.filename, :width => "95"}/ 
          .product-description 
          %p 
           %a{:href => "#"} 
          %p 
           See all from 
           %a{:href => category_path(:id => product.category.id)} 
           = product.category.label 
     =render "layouts/sidebar_left" 
     =render "layouts/sidebar_right" 

为了提高我想用助手的这种效率,但我不知道我怎么能在没有在products_helper.rb文件中编写HAML代码的情况下做到这一点。

有什么想法,我该如何做到这一点?

+0

我不认为你可以不丑陋。为什么不使用偏分量? –

回答

1

下面的一些用于优化,其他用于清理。

  1. Eager-load your associations减少DB查询次数。

    @products = Product.includes(:category).all 
    @products.each do |product| 
        puts product.category.name 
    end 
    
  2. 创建三列布局模板。除了.col-main以外的所有视图模板中包含所有内容,并且在您的布局模板.col-main内移动yield。从视图模板中移除布局特定的HAML。

  3. 使用image_taglink_to查看帮助。这可能比自己定义标签要慢,但是再次使用HAML is known to be slower than ERB

    %a{:href => '/hyperlink/url'} 
        = "hyperlink text" 
    
    = link_to 'hyperlink text', '/hyperlink/url' 
    
  4. Take advantage of path generation helpers.

    = category_path(:id => @category.id) 
    = category_path(@category) 
    
  5. 移动标记和代码为产品表格单元格部分的图。