我通常会这样写助手:
- def bloco_vazio (texto = "",btn = "",args={})
- titulo = content_tag :h3,"Vazio!"
- p = content_tag :p,texto
- content_tag :div,(titulo + tag(:hr) + p + btn ),args
- end
但我经常看到人们使用其他方法,如:
- def flash_notice
- html = ""
- unless flash.empty?
- flash.each do |f|
- html << "<div class='alert alert-#{f[:type].to_s}'>"
- html << "<a class='close' data-dismiss='alert'>×</a>"
- html << f[:text].to_s
- html << "</div>"
- end
- end
- html
- end
要么
- def a_helper (some_text ="")
- %{ <h3>some title</h3>
- <p>#{some_text}</p>
- }%
- end
我过去使用了这两个持续时间并遇到了一些问题,然后开始使用content_tag和tag helpers,即使我仍然需要使用.html_safe方法.
有没有标准的方法来建立帮助者?
解决方法
如果html超过1行,我通常将html放在部分中,并使用自定义帮助器方法调用它
视图
- <= display_my_html(@item,{html_class: "active"}) %>
帮手
- def display_my_html(item,opts={})
- name = item.name.upcase
- html_class = opts.key?(:html_class) ? opts[:html_class] : "normal"
- render "my_html",name: name,html_class: html_class
- end
局部
- <div class="<%= html_class %>">
- <span class="user">
- <%= name %>
- </span>
- </div>