0

How to mark as not safe only the variable that is passed into the translation method, when using i18n gem in Ruby on Rails framework?

For example:

t(
  'safe', 
  default: 'Unsafe <b>%{unsafe_variable}</b> and safe %{safe_variable}', 
  unsafe_variable: "<script>alert('unsafe');</script>", 
  safe_variable: '<strong>safe</strong>'
)

Should return

Unsafe <b>&lt;script&gt;alert('unsafe');&lt;/script&gt;</b> and safe <strong>safe</strong>
Dmitry Polushkin
  • 3,283
  • 1
  • 38
  • 44

1 Answers1

2

If you know in advance which one is safe and which one is unsafe, you can simply use the h helper to force escape the unsafe variable.

t('safe', default: 'Unsafe <b>%{unsafe_variable}</b> and safe %{safe_variable}', 
  unsafe_variable: h("<script>alert('unsafe');</script>"), 
  safe_variable: '<strong>safe</strong>'
)
Marc Lainez
  • 3,070
  • 11
  • 16