Welcome to mirror list, hosted at ThFree Co, Russian Federation.

gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorWinnie Hellmann <winnie@gitlab.com>2017-09-26 12:46:59 +0300
committerWinnie Hellmann <winnie@gitlab.com>2017-10-03 15:46:19 +0300
commitb509588a28d0a102f4ad4b97d91c5b5944946834 (patch)
tree1ace10c95ed2573f14927ddee014c562ab987621 /app/assets/javascripts/locale
parent92173ac55cd921a65ce137e238ed8bc4474aaccb (diff)
Add basic sprintf implementation to JavaScript
Diffstat (limited to 'app/assets/javascripts/locale')
-rw-r--r--app/assets/javascripts/locale/index.js3
-rw-r--r--app/assets/javascripts/locale/sprintf.js26
2 files changed, 29 insertions, 0 deletions
diff --git a/app/assets/javascripts/locale/index.js b/app/assets/javascripts/locale/index.js
index 7ba676d6d20..29dcd64df87 100644
--- a/app/assets/javascripts/locale/index.js
+++ b/app/assets/javascripts/locale/index.js
@@ -1,5 +1,7 @@
import Jed from 'jed';
+import sprintf from './sprintf';
+
/**
This is required to require all the translation folders in the current directory
this saves us having to do this manually & keep up to date with new languages
@@ -67,4 +69,5 @@ export { lang };
export { gettext as __ };
export { ngettext as n__ };
export { pgettext as s__ };
+export { sprintf };
export default locale;
diff --git a/app/assets/javascripts/locale/sprintf.js b/app/assets/javascripts/locale/sprintf.js
new file mode 100644
index 00000000000..003cbe820d6
--- /dev/null
+++ b/app/assets/javascripts/locale/sprintf.js
@@ -0,0 +1,26 @@
+import _ from 'underscore';
+
+/**
+ Very limited implementation of sprintf supporting only named parameters.
+
+ @param input (translated) text with parameters (e.g. '%{num_users} users use us')
+ @param parameters object mapping parameter names to values (e.g. { num_users: 5 })
+ @param escapeParameters whether parameter values should be escaped (see http://underscorejs.org/#escape)
+ @returns {String} the text with parameters replaces (e.g. '5 users use us')
+
+ @see https://ruby-doc.org/core-2.3.3/Kernel.html#method-i-sprintf
+ @see https://gitlab.com/gitlab-org/gitlab-ce/issues/37992
+**/
+export default (input, parameters, escapeParameters = true) => {
+ let output = input;
+
+ if (parameters) {
+ Object.keys(parameters).forEach((parameterName) => {
+ const parameterValue = parameters[parameterName];
+ const escapedParameterValue = escapeParameters ? _.escape(parameterValue) : parameterValue;
+ output = output.replace(new RegExp(`%{${parameterName}}`, 'g'), escapedParameterValue);
+ });
+ }
+
+ return output;
+}