1

ヘルパーメソッドで私はこれを持っています:

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 を使用しています。

4

1 に答える 1

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

つまり、string/SafeBufferに属性をraw設定するだけです。エスケープは、を返すhtml_safe文字列に対してのみ実行されます。文字列はエスケープする機会があるたびに戻るため、文字列がエスケープされることはありません。string.html_safe?falsetrue

解像度:

補間または連結によって新しい文字列を作成します。これにより、html_safeが再びfalseに設定され、文字列がエスケープされます。

詳細については、SafeBuffersに関するこのガイドを確認し、ドキュメントをお読みください。

于 2012-08-29T23:46:47.513 に答える