2010-05-27 39 views
3

我有這個漂亮類ErrorFormBuilder,讓我加在表單視圖附近的相應字段錯誤描述:跳過HTML逃逸在鐵路自label_tag幫手3

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>" 

默認情況下,在視圖中逃脫...... 我試圖添加{:逃生=>假}選項:

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

沒有成功

有沒有辦法繞過這種行爲?

謝謝

回答

9

你有沒有嘗試過讓你的字符串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,向下滾動到「你需要知道什麼」接近底部:

在一般情況下,你可以完全按照之前建立自己的Rails應用程序。 Rails將自動轉義它不創建的任何字符串。在幾乎所有情況下,這是正確的行爲,無需進一步修改。

如果Rails正在轉義一個你不想轉義的字符串,只需標記它是安全的。如果你在助手中創建一個字符串,你可能想要標記它的一部分是安全的。

我無法測試這是否適用於您的次級輔助工具,但我會這麼認爲。

8

只是使用<%= raw your_variable_here %>