我有一个显示项目列表的视图。每个项目都有几个地方,您可以单击以启动相同的Bootstrap模式。我想编写一个帮助方法来替换冗余代码,但我是haml的新手,并且不能让helper方法起作用。我曾尝试阅读有关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
答案 0 :(得分: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。