-
Notifications
You must be signed in to change notification settings - Fork 9.4k
Description
Preconditions
Magento version: 2.1.2
Translate a string in javascript, for example like this (taken from mage/validation.js
):
validator.passwordErrorMessage = $.mage.__(
"Minimum of different classes of characters in password is %1." +
" Classes of characters: Lower Case, Upper Case, Digits, Special Characters."
).replace('%1', passwordMinCharacterSets);
The string should be for example concatted in JavaScript with the +
sine.
Steps to reproduce
Look up the page where the translated string should appear (in this case: the register account page)
Expected result
The password error message is translated
Actual result
The password error message is not translated
Cause
The root cause of this, is the regex that selects JS strings for translation, as found in: /app/code/Magento/Translation/etc/di.xml
. It's is very buggy and not fail safe. It skips every string that is not strictly formatted according to this regex. In this case the '+' sign causes the string to be skipped by the regex, but there are many more cases where this regex is skipped in JS files (e.g. iteration over parts of strings to translate them). See:
magento2/app/code/Magento/Translation/etc/di.xml
Lines 60 to 62 in 0be91a5
<item name="i18n_translation" xsi:type="string"><![CDATA[~i18n\:\s*(["'])(.*?)(?<!\\)\1~]]></item> | |
<item name="mage_translation_widget" xsi:type="string">~\$\.mage\.__\((['"])(.+?)\1\)~</item> | |
<item name="mage_translation_static" xsi:type="string">~\$t\((["'])(.+?)\1\)~</item> |
Looks like the implementation of the js-translation.json
file should be a bit refactored.
Workaround
A workaround I use in production is to create a JS file which calls the$.mage.__()
with the string that I would like to translate, e.g.:
// HACK to make strings translatable, so the Mage Translate regex picks them up for JS translation
$.mage.__("Minimum of different classes of characters in password is %1. Classes of characters: Lower Case, Upper Case, Digits, Special Characters.");
$.mage.__("Minimum length of this field must be equal or greater than %1 symbols. Leading and trailing spaces will be ignored.");