Versions Compared
Key
- This line was added.
- This line was removed.
- Formatting was changed.
This class provides methods returning translated messages. This class has no constructor; the methods can be accessed by using the s_i18n global objectДанный класс содержит методы, возвращающие переведенные сообщения. У него нет конструктора, поэтому доступ к методам осуществляется через глобальный объект s_i18n.
getMessage(msgKey, config, callback)
This method returns a string containing a message in the user language for a specified string. If this string has no localization for the current language, or it does not exist at all, the method returns the msgKey value.
The msgKey parameter should pass the string for translation, and the callback parameter is the function that is executed after the server response.
Parameter(s):
NameTypeMandatoryDefault ValuemsgKeyStringYNconfigObjectN''callbackFunctionNNИспользуйте метод, чтобы вернуть строку с данными, переданными в msgKey. Возращенные данные переведены на язык пользователя. Если в системе не существует такой строки, или её перевода на текущий язык, метод возвращает значение msgKey.
Параметр msgKey содержит строку для перевода, а параметр callback является функцией, которая выполняется после ответа сервера.
Параметры:
Название | Тип | Обязательное | Значение по умолчанию |
---|---|---|---|
msgKey | String | Да | Нет |
config | Object | Нет | { } |
callback | Function | Нет | Нет |
Параметр config представляет собой объект, содержащий три параметра:
Название | Тип | Обязательное | Значение по умолчанию |
---|---|---|---|
language | String | Нет |
The config parameter is implemented as an object containing three other parameters:
Name | Type | Mandatory | Default Value |
---|---|---|---|
language | String | N | '' |
category | String | NНет | 'app' |
params | Object | NНет | ''{ } |
The language parameter can take on the values specified in the Languages Параметр language принимает значения, указанные в таблице Язык (sys_language) dictionary. If it is not specified, the current user's language is used when the method is called.. Если он не указан, метод будет использовать текущий язык пользователя.
Параметр category принимает значения, хранящиеся в записи таблицы Исходные сообщения The category parameter can take on the values specified in the Category field of the Source Message (source_message) table recordв поле Категория.
The params parameter provides an object service to aggregate the language and category parameter values and to keep the placeholder values from the msgKey parameter (see the code example below).
NoteЕслив сообщении присутствуют местозаполнители, а у объекта params есть ключ, совпадающий с заполнителем, то в итоговое сообщение будет подставлено его значение.
Как правило, параметр config не является обязательным, поэтому для получения перевода можно использовать функцию обратного вызова
Generally, the config parameter is non-mandatory, so you can use callback functions to get translations:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
await s_i18n.getMessage('Description', (response) => {console.log(response)});
// DescriptionОписание |
Note |
---|
Note that this method is asynchronous; for better performance, use the await keyword as in the code example below. |
Return:
TypeDescriptionStringThis method returns a message, optionally translated in the language specified.Метод является асинхронным. Для оптимальной работы используйте ключевое слово await, как в примере ниже. |
Возвращаемое значение:
Тип | Описание |
---|---|
String | Метод возвращает сообщение, переведенное на указанный язык, соответствующее параметру language. |
ПримерExample:
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
if (!s_form.getValue('condition')) { await s_i18n.getMessage('Specify conditions in "Condition" [condition] field.', (response) => { s_form.addErrorMessage(response); }); return false; } |
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
const serviceNameValue = 'EmailПочта'; s_i18n.getMessage('Sorry, The {serviceName} Service Is Temporarily Unavailable', {params: {"serviceName": serviceNameValue}, language: "enru", category: "app"}, (response) => console.log(response)); // SorryИзвините, Emailпочта Service Is Temporarily Unavailableвременно недоступна |
getMessages(msgKeys, config, callback)
This method returns an array of strings that contains messages in a user language. If these strings do not have localization for the current language, or they do not exist at all, the method returns msgKey string values.
The msgKeys parameter should pass the array of strings for translation, and the callback parameter is the function that is executed after the server response.
Parameter(s):
NameTypeMandatoryDefault ValuemsgKeyStringYNconfigObjectN''callbackFunctionNNИспользуйте метод, чтобы вернуть массив строк, содержащих сообщения на языке пользователя. Если строка из массива не локализована для текущего языка или не существует, метод возвращает её исходное значение.
Параметр msgKeys передает массив строк на перевод. Параметр callback является функцией, которая выполняется после ответа сервера.
Параметры:
Название | Тип | Обязательное | Значение по умолчанию |
---|---|---|---|
msgKeys | Array of Strings | Да | Нет |
config | Object | Нет | { } |
callback | Function | Нет | Нет |
Параметр config представляет собой объект, содержащий три параметра:
Название | Тип | Обязательное | Значение по умолчанию |
---|---|---|---|
language | String | Нет |
The config parameter is implemented as an object containing three other parameters:
Name | Type | Mandatory | Default Value |
---|---|---|---|
language | String | N | '' |
category | String | NНет | 'app' |
params | Object | NНет | ''{ } |
The language parameter can take on the values specified in the Languages Параметр language принимает значения, указанные в таблице Язык (sys_language) dictionary. If it is not specified, the current user's language is used when the method is called.. Если он не указан, метод будет использовать текущий язык пользователя.
Параметр category принимает значения, хранящиеся в записи таблицы Исходные сообщения The category parameter can take on the values specified in the Category field of the Source Message (source_message) table recordв поле Категория.
The params parameter provides an object service to aggregate the language and category parameter values and to keep the placeholder values from the msgKey parameter (see the code example below).
Note |
---|
Note that this method is asynchronous; for better performance, use the await keyword as in the code example below. |
Return:
TypeDescriptionArray of stringsThis method returns an array of messages, optionally translated into the language specified.Еслив сообщении присутствуют местозаполнители, а у объекта params есть ключ, совпадающий с местозаполнителем, то в итоговое сообщение будет подставлено его значение.
Note |
---|
Метод является асинхронным. Для оптимальной работы используйте ключевое слово await,как в примере ниже. |
Возвращаемое значение:
Тип | Описание |
---|---|
Array of Strings | Метод возвращает массив строк, которые могут быть переведены на язык, соответствующий параметру language. |
ПримерExample:
Code Block | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
const data = {}; const btnTitles = ['Accept', 'Cancel']; await s_i18n.getMessages(btnTitles, (response) => { [data.acceptBtnTitle, data.cancelBtnTitle] = response; }); console.log(JSON.stringify(data)); // {"acceptBtnTitle":"AcceptПринять","cancelBtnTitle":"CancelОтмена"} |
Note | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Note that if you use the same placeholders for different messages, the getMessages() method output contains the same values on their place.При использовании одного и того же местозаполнителя в разных сообщениях метод getMessages() возвращает одинаковые значения. const dayOfWeek = ['Monday', 'Wednesday', 'Friday']; s_i18n.getMessages(dayOfWeek, {language: 'ru'}, (response) => {console.log(response.join('-'))}); // Понедельник-Среда-Пятница
Метод возвращает сообщения:
|
Table of Contents | ||||
---|---|---|---|---|
|