gpt4 book ai didi

ruby - 在 Rail 3 中的自定义 label_tag 助手中跳过 HTML 转义

转载 作者:数据小太阳 更新时间:2023-10-29 07:40:59 24 4
gpt4 key购买 nike

我有一个很好的 ErrorFormBuilder 类,它允许我在表单 View 中的相应字段附近添加错误描述:

    class ErrorFormBuilder < ActionView::Helpers::FormBuilder
#Adds error message directly inline to a form label
#Accepts all the options normall passed to form.label as well as:
# :hide_errors - true if you don't want errors displayed on this label
# :additional_text - Will add additional text after the error message or after the label if no errors
def label(method, text = nil, options = {})
#Check to see if text for this label has been supplied and humanize the field name if not.
text = text || method.to_s.humanize
#Get a reference to the model object
object = @template.instance_variable_get("@#{@object_name}")

#Make sure we have an object and we're not told to hide errors for this label
unless object.nil? || options[:hide_errors]
#Check if there are any errors for this field in the model
errors = object.errors.on(method.to_sym)
if errors
#Generate the label using the text as well as the error message wrapped in a span with error class
text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"
end
end
#Add any additional text that might be needed on the label
text += " #{options[:additional_text]}" if options[:additional_text]
#Finally hand off to super to deal with the display of the label
super(method, text, options)
end
end

但是 HTML :

text += " <br/><span class=\"error\">#{errors.is_a?(Array) ? errors.first : errors}</span>"

在 View 中默认转义...我尝试添加 {:escape => false} 选项:

super(method, text, options.merge({:escape => false}))

没有成功

有什么办法可以绕过这种行为吗?

谢谢

最佳答案

你试过让你的字符串 html_safe 吗?

irb(main):010:0> a = "A string"
=> "A string"
irb(main):011:0> a.html_safe?
=> false
irb(main):012:0> b = a.html_safe
=> "A string"
irb(main):013:0> b.html_safe?
=> true

参见 http://www.railsdispatch.com/posts/security并向下滚动到底部附近的“您需要了解的内容”:

In general, you can build your Rails app exactly as before. Rails will automatically escape any Strings that it doesn’t create. In almost all cases, this is the right behavior, with no further modifications required.

If Rails is escaping a String that you want to pass through without escaping, simply mark it safe. If you create a String in a helper, you may want to mark parts of it as safe.

我无法测试这是否适用于您的子类助手,但我认为可以。

关于ruby - 在 Rail 3 中的自定义 label_tag 助手中跳过 HTML 转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2923625/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com