【问题标题】:Using a Haml helper method with haml_tag to make a rails view DRY-er使用带有 haml_tag 的 Haml 辅助方法来制作 Rails 视图 DRY-er
【发布时间】:2015-02-18 20:26:45
【问题描述】:

我有一个显示项目列表的视图。每个项目都有几个地方,您可以单击以启动相同的 Bootstrap 模式。我想编写一个辅助方法来替换冗余代码,但是我是 haml 的新手,无法让辅助方法工作。我尝试阅读有关 Haml::Helpers 的文档,但不清楚所有内容如何组合在一起。

冗余代码

{"data-target" => "#opportunityModal#{opportunity.id}", 
 "data-toggle" => "modal",       
  href: "#opportunityModal#{opportunity.id}"}

包装在辅助方法中的冗余代码

module OpportunitiesHelper
    def modal_tag (type)
        haml_tag type, {"data-target" => "#opportunityModal#{opportunity.id}", "data-toggle" => "modal", href: "#opportunityModal#{opportunity.id}"}
    end
end

当前视图的片段

%li
.item.col-sm-4
  %button{"data-target" => "#opportunityModal#{opportunity.id}", 
         "data-toggle" => "modal", 
          href: "#opportunityModal#{opportunity.id}"} 
      Quick View

.col-sm-8
  %a{"data-target" => "#opportunityModal#{opportunity.id}", 
           "data-toggle" => "modal", 
            href: "#opportunityModal#{opportunity.id}"}
    = opportunity.title

= render :partial => "opportunities/modal", :locals => { :opportunity => opportunity}

使用辅助方法的相同视图

%li
.item.col-sm-4
  -modal_tag(:button)
      Quick View

.col-sm-8
  -modal_tag(:a)
    = opportunity.title

= render :partial => "opportunities/modal", :locals => { :opportunity => opportunity}

我尝试使用辅助方法时出现错误

syntax error, unexpected keyword_ensure, expecting end-of-input

【问题讨论】:

    标签: ruby-on-rails haml


    【解决方案1】:

    你肯定需要一个块。

    - modal_helper(:a, opportunity.id) do
      Quick View
    

    我会这样做:

    def modal_helper(type, id, &block)
      content_tag(type, href: "#opportunityModal#{id}", data: { target: "#opportunityModal#{id}", toggle: "modal" }) &block
    end
    

    这应该让你非常接近。块和输出 html 可能有些奇怪。例如,您可能需要 html_safe。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 2011-07-07
      • 1970-01-01
      • 1970-01-01
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      相关资源
      最近更新 更多