Remove html tags from I18n "translation missing" messages
Asked Answered
G

2

7

Consider the following code in a view:

<%= link_to 'Delete!', item ,  :confirm => t('action.item.confirm_deletion'), :method => :delete %>

It will normally come out as:

<a href="/items/123" data-confirm="Confirm deletion?" data-method="delete" rel="nofollow">Delete!</a>

But if the translation for action.item.confirm_deletion is missing for some reason (incomplete yml-file, typos, etc.) it comes out as:

<a href="/items/123" data-confirm="<span class="translation_missing" title="translation missing: sv.action.item.confirm_deletion">Confirm Deletion</span>" data-method="delete" rel="nofollow">Delete!</a>

which is invalid html, and user will see broken html tags on the homepage. It may also be a security risk in some cases.

I know that I could use apply some escaping on every call to the I18n.t function, but that feels unnecessarily repetitive for the task.

So my question is: Is there a way to make the "translation missing"-messages not contain html code.

Greenland answered 7/8, 2012 at 10:25 Comment(2)
Not too good and answer since it is per-t() call: t('action.item.confirm_deletion', :default => 'Are you sure you want to delete this thing?')Horseflesh
Thanks anyway! It's always good to know that possibility.Greenland
I
4

There are multiple solutions for you.

You can alias the translation method to your own and call with the custom :default value (I would prefer this way):

module ActionView
  module Helpers
    module TranslationHelper
      alias_method :translate_without_default :translate

      def translate(key, options = {})
        options.merge!(:default => "translation missing: #{key}") unless options.key?(:default)
        translate_without_default(key, options)
      end
    end
  end
end

Or you can overwrite the default value:

module I18n
  class MissingTranslation
    def html_message
      "translation missing: #{keys.join('.')}"
    end
  end
end
Islek answered 7/8, 2012 at 11:29 Comment(2)
Thanks! According to your second tip, i wrote a plain text version, replacing the empty quotes with %(Translation missing: #{keys.join('.')})Greenland
Overwriting the default value is not working on rails 4.2!Dividend
D
1

In rails 4.2 you have to redefine the translate helper in the view:

https://github.com/rails/rails/blob/v4.2.5/actionview/lib/action_view/helpers/translation_helper.rb#L78

In rails 5 you can set in your application.rb:

config.action_view.debug_missing_translation = false
Dividend answered 29/12, 2015 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.