Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Данный класс позволяет возвращать переведенные сообщения. У него нет конструктора, доступ к методам осуществляется через s_i18n глобальный объект.

getMessage(msgKey, config, callback)


Этот метод возвращает перевод заданной строки в форме строки, содержащей сообщение на языке пользователя. Если строка не существует или не имеет перевода на текущий язык, метод возвращает значение msgKey.

Параметр msgKey отправляет строку на перевод, а параметр callback является функцией, которая выполняется после ответа сервера.


Параметры:

НазваниеТипОбязательноеДефолтное значение
msgKeyСтрокаДН
configОбъектН''
callbackФункцияНН


Параметр config применяется в качестве объекта, содержащего три параметра:

НазваниеТипОбязательноеДефолтное значение
languageСтрокаН''
categoryСтрокаН'app'
paramsОбъектН''

Параметр language может принимать значения, указанные в словаре Languages (sys_language). Если он не указан, метод будет вызывать текущий язык пользователя.

Параметр category может принимать значения, указанные в записи таблицы Source Message (source_message) в поле Category .

Параметр params позволяет объекту получать значения параметров language и category для того, чтобы сохранить значение плэйсхолдера из параметра msgKey. 

Пример:

Note

Как правило, параметр config не является обязательным, поэтому для получения перевода можно использовать функции обратного вызова:

Code Block
languagejs
themeEclipse
titlegetMessage
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Данный метод является асинхронным. Для оптимальной работы используйте ключевое слово await как в примере ниже.


Return:

TypeDescription
StringThis method returns a message, optionally translated in the language specified.


Example:

Code Block
languagejs
themeEclipse
titlegetMessage
linenumberstrue
if (!s_form.getValue('condition')) {
  await s_i18n.getMessage('Specify conditions in "Condition" [condition] field.', (response) => {
    s_form.addErrorMessage(response);
  });
  return false;
}


Code Block
languagejs
themeEclipse
titlegetMessage
linenumberstrue
const serviceNameValue = 'Email';
s_i18n.getMessage('Sorry, {serviceName} Service Is Temporarily Unavailable', {params: {"serviceName": serviceNameValue}, language: "en", 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 Value
msgKeyStringYN
configObjectN''
callbackFunctionNN


The config parameter is implemented as an object containing three other parameters:

NameTypeMandatoryDefault Value
languageStringN''
categoryStringN'app'
paramsObjectN''

The language parameter can take on the values specified in the Languages (sys_language) dictionary. If it is not specified, the current user's language is used when the method is called.

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:

TypeDescription
Array of stringsThis method returns an array of messages, optionally translated into the language specified.


Example:

Code Block
languagejs
themeEclipse
titlegetMessages
linenumberstrue
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.

Code Block
languagejs
themeEclipse
titlegetMessages
linenumberstrue
const dayOfWeek = ['Monday', 'Wednesday', 'Friday'];
s_i18n.getMessages(dayOfWeek, {language: 'ru'}, (response) => {console.log(response.join('-'))});

// Понедельник-Среда-Пятница



Table of Contents
absoluteUrltrue
classfixedPosition