How to make JavaScript strings translatable (localizable) in Magento 2
To make JavaScript strings translatable or localizable in Magento 2, use
1 |
$.mage.__ |
For instance:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
this._initSortableSelections(); this._bindCheckboxHandlers(); this._bindReadOnlyMode(); this._addValidation(); }, _addValidation: function () { $.validator.addMethod( 'required-option-select', function (value) { return (value !== ''); }, $.mage.__('Select type of option.')); $.validator.addMethod( 'required-option-select-type-rows', function (value, element) { var optionContainerElm = element.up('div[id*=_type_]'), selectTypesFlag = false, selectTypeElements = $('#' + optionContainerElm.id + ' .select-type-title'); selectTypeElements.each(function () { if (!$(this).closest('tr').hasClass('ignore-validate')) { selectTypesFlag = true; |
Note that you should place the translation in the i18n
It is also necessary to mention that there are some Magento 2 core modules that translate JavaScript strings as follows:
define
/ require
mage/translate
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * Copyright © 2015 Magento. All rights reserved. * See COPYING.txt for license details. */ /*jshint jquery:true*/ define([ "jquery", "braintree", 'mage/translate', "jquery/ui" ], function ($, braintree, $t) { 'use strict'; $.widget('mage.braintreeEditForm', { options: { backUrl: '', formId: '#form-validate', creditCardTypeId: '#credit_card_type', deviceDataId: '#device_data', |
and
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
success: function (response) { $('body').trigger('processStop'); if (response instanceof Object) { if (response.success) { $('body').trigger('processStart'); window.location = self.options.backUrl; } } }, error: function (response) { alert($t('There was error during saving card data')); } }); } else { //handle error $('body').trigger('processStop'); alert($t('There was error during saving card data')); } }); } } |
Please note that you have to deal with the autogenerated js-translation.json
file, so it is necessary to delete it and flush cache to make the system become able to recheck your new interface strings and the dictionary. It will create a new js-translation.json
file. Also note that the js-translation.json
file is generated only if you have a language package for your current language.
More tips from Magento 2 cookbook