How To Avoid Ruby on Rails content_for Converting Characters to HTML Entities
One thing that is quite annoying, but understandable, is content_for
- https://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for - converting characters to HTML entities as I thought the string is just marked as HTML safe with some magic, but instead my string is escaped two times which breaks the presentation.
When I looked closer, the behavior makes sense since the result of content_for
is just a string which is or isn’t marked as HTML safe. And =
inside escapes stuff.
The following example is in Slim language, but the same goes also with ERB template.
- content_for :page_title do
= @article.title
This is debug from application.html.erb
layout:
[1] pry(#<#<Class:0x00007faf248f1d78>>)> @article.title
=> "AAAA'BBBB"
[2] pry(#<#<Class:0x00007faf248f1d78>>)> yield(:page_title)
=> "AAAA'BBBB"
That is converted in = yield(:page_title)
to AAAA∓#39;BBBB
which means a browser will show this: AAAA'BBBB
.
Since it is escaped in title anyways, we don’t need double escapes, we can set a string in content_for
to not escape with raw
:
- content_for :page_title do
= raw @article.title
[1] pry(#<#<Class:0x00007f21925a6eb8>>)> yield(:page_title)
=> "AAAA'BBBB"
Now it is escaped to AAAA'BBBB
and shown in a browser as AAAA'BBBB
.
And that’s what I wanted.
Add Comment