Mind Dump, Tech And Life Blog
written by Ivan Alenko
published under license CC4-BY
posted at 19. Apr '24

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&#39;BBBB"

That is converted in = yield(:page_title) to AAAA&mp;#39;BBBB which means a browser will show this: AAAA&#39;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&#39;BBBB and shown in a browser as AAAA'BBBB.

And that’s what I wanted.

Add Comment