Rails 中的助手 - 构建 html 字符串时的最佳方法是什么? [英] Helpers in Rails - What's the best approach when building the html string?

查看:43
本文介绍了Rails 中的助手 - 构建 html 字符串时的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通常这样写助手:

 def bloco_vazio (texto = "", btn = "", args={})标题 = content_tag :h3, "Vazio!"p = content_tag :p, 文本content_tag :div, (titulo + tag(:hr) + p + btn ), args结尾

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

 def flash_noticehtml = ""除非 flash.empty?flash.each 做 |f|html <<"<div class='alert alert-#{f[:type].to_s}'>"html <<"<a class='close' data-dismiss='alert'>×</a>"html <<f[:text].to_shtml <<</div>"结尾结尾html结尾

def a_helper (some_text ="")%{ <h3>一些标题</h3><p>#{some_text}</p>}%结尾

我过去使用过这两个鞋楦,遇到了一些问题,然后开始使用 content_tag 和标签助手,即使有时我仍然必须使用 .html_safe 方法.

有没有标准的方法来构建助手?

解决方案

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

查看

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

帮手

def display_my_html(item, opts={})名称 = item.name.upcasehtml_class = opts.key?(:html_class) ?opts[:html_class] : 正常"呈现my_html",名称:名称,html_class:html_class结尾

部分

<span class="user"><%=姓名%></span>

I usually write helpers that way:

  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

But i commonly see people using other approaches, like:

 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

or

def a_helper (some_text ="")
  %{ <h3>some title</h3>
      <p>#{some_text}</p>    
  }%
end

I used these two lasts in the past and ran into some problems then started using the content_tag and tag helpers, even that i still have to use the .html_safe method sometimes.

Is there a standard way to build helpers?

解决方案

If html is longer than 1 line, i usually put the html in a partial and call it with a custom helper method

view

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

helper

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

partial

<div class="<%= html_class %>">
  <span class="user">
    <%= name %>
  </span>
</div>

这篇关于Rails 中的助手 - 构建 html 字符串时的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆