在我的应用程序中,我有重复的模态等代码,就像这样:
<% @documents.each do |d| %>
<div class="modal hide fade" id="deleteModal<%= d.id %>">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="deleteModal<%= d.id %>Label">Deleting <%= d.title %></h3>
</div>
<div class="modal-body">
<p>Make sure you want to delete <%= d.title %> before doing so.</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<%= link_to 'Delete', d, method: :delete, class: "btn btn-danger" %>
</div>
</div>
<% end %>
是否有设计模式来鼓励像这样的实例的动态代码?也许jQuery或类似的东西?这对我来说非常浪费。或者这不重要吗?
答案 0 :(得分:1)
一种解决方案是使用TagHelper编写辅助方法(如果模态结构永远不会更改)。更具体地说,通过嵌套content_tag - http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag
类似的东西:
modal_helper.rb
module ModalHelper
def delete_modal(d)
@id = d.id
@title = d.title
content_tag(:div, header + body + footer(d), class: "modal hide fade", id: "deleteModal#{@id}")
end
def header
content_tag(:div, content_tag(:button, "x", class: "close", type:"button", data-dismiss:"modal", aria-hidden:"true") + content_tag(:h3, "Deleting #{@title}", id: "deleteModal#{@id}Label"), class: "modal-header")
end
def body
content_tag(:div, content_tag(:p, "Make sure you want to delete #{@title} before doing so."), class: "modal-body")
end
def footer(d)
content_tag(:div, content_tag(:button, "Cancel", class: "btn", data-dismiss:"modal", aria-hidden:"true") + (link_to 'Delete', d, method: :delete, class: "btn btn-danger"), class: "modal-footer")
end
end
然后简单地说:
<%= @documents.each {|d| delete_modal(d)} %>
如果您想要不同的信息,您可以通过您选择的任何参数。
希望这有帮助!