Reputation: 4499
According to ruby docs, the translate
(or t
) helper delegates to I18n#translate
but also performs several additional functions, among which is: "it’ll mark the translation as safe HTML if the key has the suffix _html
".
I would expect that it should work equally in both views and in controllers, but in my experience it doesn't: t(:hello_html)
does work as expected in views (marks the translation as html_safe), but it does not mark the result as safe html when invoked from a controller.
To reproduce the problem you could add hello_html: '<i>Hello world</i>'
to your locales/en.yml
and flash.now[:notice] = t(:hello_html)
to any convenient action of any controller. For me that resulted in an escaped html markup in a flash messages area which was an unexpected outcome for me.
My questions are:
(Tested in rails 3.2.11 and 3.2.13)
Upvotes: 4
Views: 1546
Reputation: 2518
You are correct about this functionality not being available to controllers given that the overloaded .t
method is defined in ActionView::Helpers::TranslationHelper
. I think this is probably an oversight as opposed to an actual bug.
Off the top of my head there are 2 ways you can get around this in your project :
Call .html_safe
in your controller (this worked for me in a quick test).
flash[:notice] = t(:hello_html).html_safe
Send the translation key as the flash message as opposed to the actual message :
Controller :
flash[:translate_notice] = :hello_html
View :
%div= t flash[:translate_notice]
Granted, the latter option might get a bit messy if you need to pass interpolations, YMMV.
Upvotes: 4