【问题标题】:How to create helper for a view which uses HAML?如何为使用 HAML 的视图创建助手?
【发布时间】:2013-10-29 17:18:11
【问题描述】:

我正在开发一个必须在主页上显示产品列表的 Web 应用程序。 为此,我有一个 ProductsController:

     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 代码,我怎么能做到这一点。

我有什么想法可以做到这一点吗?

【问题讨论】:

  • 我认为你不能不让它变得丑陋。为什么不使用部分?

标签: ruby-on-rails haml


【解决方案1】:

以下一些用于优化,另一些用于清理。

  1. Eager-load your associations 减少数据库查询的数量。

    @products = Product.includes(:category).all
    @products.each do |product|
      puts product.category.name
    end
    
  2. 创建三栏布局模板。让这包括您的视图模板中的所有内容,除了.col-main 内的内容,并将yield 移动到.col-main 内的布局模板中。从您的视图模板中删除特定于布局的 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. 将产品表格单元格的标记和代码移动到部分视图。

【讨论】:

    猜你喜欢
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 2010-11-06
    • 1970-01-01
    • 2016-11-02
    相关资源
    最近更新 更多