使用带有 haml_tag 的 Haml 辅助方法来制作 rails 视图 DRY-er
Using a Haml helper method with haml_tag to make a rails view DRY-er
我有一个显示项目列表的视图。每个项目都有多个位置,您可以在其中单击以启动相同的 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
你肯定需要一个街区。
- 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。
我有一个显示项目列表的视图。每个项目都有多个位置,您可以在其中单击以启动相同的 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
你肯定需要一个街区。
- 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。