【问题标题】:Better way than ''.html_safe when building html string in Rails?在 Rails 中构建 html 字符串时比 ''.html_safe 更好的方法?
【发布时间】:2012-05-18 19:09:56
【问题描述】:

典型模式:

out = ''.html_safe # or ActiveSupport::SafeBuffer.new
out << content_tag(...) if foo
out << 'hello, 1 < 2' # will be escaped properly
out << content_tag(...) if bar

out

这很好用。有没有比这更好/更短/更好的方法,特别是调用''.html_safe

【问题讨论】:

    标签: ruby-on-rails-3 html-safe


    【解决方案1】:

    我不会对此表示赞同,因为我认为这不是您真正想要的答案。但我想我还是会分享一些想法以供考虑。

    这实际上可能更难阅读,但我有兴趣查看基准测试的结果与您问题中使用的实现。

    out = "#{content_tag(...) if foo}" <<
          "hello, 1 < 2" <<
          "#{content_tag(...) if bar}"
    out.html_safe
    

    另外,我不熟悉html_safe 的内部结构,如何知道在最初设置它与返回之前是否有区别。我猜html_safe 的初始设置会更快,因为您复制的是零长度字符串而不是可能的长字符串,但为了论证:

    out = '' # or ActiveSupport::SafeBuffer.new
    out << content_tag(...) if foo
    out << 'hello, 1 < 2' # will be escaped properly
    out << content_tag(...) if bar
    out.html_safe
    

    考虑到这一点,我会考虑从上面修改我的原始代码,甚至更进一步:

    "#{content_tag(...) if foo}".html_safe <<
    "hello, 1 < 2" <<
    "#{content_tag(...) if bar}"
    

    再一次,不是很可读,但我想我会把它扔在那里作为思考的食物。

    【讨论】:

    • 您的前两个示例不会逃脱&lt;。你的最后一个仍然有一个html_safe,所以什么也没得到......
    • 我很困惑......他们三个都打电话给html_safe。也许我误解了你原来的问题。你想要完成(或避免)什么?
    • "".html_safe + "&lt;" # =&gt; "&amp;lt;""&lt;".html_safe # =&gt; "&lt;"
    猜你喜欢
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多