2012-08-29 19 views
1

在一個輔助方法後逃離我有這樣的:Rails的:無法使用content_for與原

content_for(:title, raw(page_title)) 

在我看來,我調用輔助方法後有這樣的:

<%= h(content_for(:title)) %> 

然而,當我這樣做,h()不HTML轉義的內容?我也試過content_for(:title).html_safehtml_escape(content_for(:title))沒有成功。

我將內容保存爲原始文件,因爲我想在單獨的視圖中訪問原始(未轉義的)內容。 我在Rails 3.0.17上。

回答

1

經過一番調查,這裏是我的結論:這完全是關於html_safe。

讓我有一些代碼解釋:

page_title.html_safe? #false 
raw(page_title).html_safe? #true - that's all that raw does 
content_for(:title, raw(page_title)) #associates :title with page_title, where page_title.html_safe? returns true 

現在,當查看調用這裏的輔助方法,是發生了什麼:

content_for(:title) #no escaping. Since page_title was stored and html_safe is true, conetnt_for will not escape 
h(content_for(:title)) #no escaping. Since the last line returned a string where html_safe? returns true, this will also not escape. 
<%= h(content_for(:title)) %> #no escaping. Same reason as above 

總之,raw只是設置html_safe屬性上的串/ SafeBuffer。轉義僅在string.html_safe?返回false的字符串上執行。由於字符串在每個轉義機會返回true,字符串永遠不會被轉義。

分辨率:

創建通過插值或串聯一個新的字符串 - 這將再次html_safe設置爲false,該字符串將被轉義。

欲瞭解更多信息,請查閱本指南SafeBuffers並閱讀docs

相關問題