經過一番調查,這裏是我的結論:這完全是關於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。