Add convenience helper method `safe_format`
What does this MR do and why?
In https://docs.gitlab.com/ee/development/i18n/externalization.html#html we encourage the use html_escape
+ html_safe
to make translated strings secure.
However, in we've enabled Style/FormatString
in !94092 (merged) and configured it to enforce format(string, args)
instead of string % args
.
# NOW with `String#%`
html_escape(_('Some %{strongOpen}bold%{strongClose} text.')) % { strongOpen: '<strong>'.html_safe, strongClose: '</strong>'.html_safe }
# THEN with `Kernel#format`
format(html_escape(_('Some %{strongOpen}bold%{strongClose} text.')), strongOpen: '<strong>'.html_safe, strongClose: '</strong>'.html_safe).html_safe
# With `SafeFormatHelper#safe_format`
safe_format('Some %{strongOpen}bold%{strongClose} text.', strongOpen: '<strong>'.html_safe, strongClose: '</strong>'.html_safe)
The implementation would take care to:
- HTML-escape passed format
format
if not marked as HTML-safe - HTML-escape passed arguments
args
if not marked as HTML-safe - Return a HTML-safe string to avoid double escaping
Refs #374091 (closed)
How to set up and validate locally
bin/rspec spec/helpers/safe_format_helper_spec.rb
MR acceptance checklist
This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.
-
I have evaluated the MR acceptance checklist for this MR.
Edited by Peter Leitzen