2013-10-29 19 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. 移動標記和代碼爲產品表格單元格部分的圖。