ruby-on-rails – Rails中的助手 – 构建html字符串时最好的方法是什么?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails中的助手 – 构建html字符串时最好的方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我通常会这样写助手:
  1. def bloco_vazio (texto = "",btn = "",args={})
  2. titulo = content_tag :h3,"Vazio!"
  3. p = content_tag :p,texto
  4. content_tag :div,(titulo + tag(:hr) + p + btn ),args
  5. end

但我经常看到人们使用其他方法,如:

  1. def flash_notice
  2. html = ""
  3. unless flash.empty?
  4. flash.each do |f|
  5. html << "<div class='alert alert-#{f[:type].to_s}'>"
  6. html << "<a class='close' data-dismiss='alert'>×</a>"
  7. html << f[:text].to_s
  8. html << "</div>"
  9. end
  10. end
  11. html
  12. end

要么

  1. def a_helper (some_text ="")
  2. %{ <h3>some title</h3>
  3. <p>#{some_text}</p>
  4. }%
  5. end

我过去使用了这两个持续时间并遇到了一些问题,然后开始使用content_tag和tag helpers,即使我仍然需要使用.html_safe方法.

有没有标准的方法来建立帮助者?

解决方法

如果html超过1行,我通常将html放在部分中,并使用自定义帮助器方法调用

视图

  1. <= display_my_html(@item,{html_class: "active"}) %>

帮手

  1. def display_my_html(item,opts={})
  2. name = item.name.upcase
  3. html_class = opts.key?(:html_class) ? opts[:html_class] : "normal"
  4.  
  5. render "my_html",name: name,html_class: html_class
  6. end

局部

  1. <div class="<%= html_class %>">
  2. <span class="user">
  3. <%= name %>
  4. </span>
  5. </div>

猜你在找的Ruby相关文章