Internationalize JavaScript code
Localization syntax
Transifex Native supports the ICU Message Format. Phrases for localization should be encapsulated in the t function as shown in the example below.
import { t } from '@transifex/native';
t('Hello');
t('Hello <b>{username}</b>', { username: 'Joe' });
Parameters and metadata
Several parameter keys can be used in order to annotate the string with metadata that will be used in Transifex. The supported parameter keys are:
- _context, to define additional context for the specific phrase. You can add a list of strings and separate them with a comma. Context data will be visible in the context tab of the editor.
- _comment, to provide instructions to the localization team working on this phrase. This information is displayed in the editor's translation area as string instructions.
- _charlimit, to add a character limit count for the translations. This information is displayed both in the editor's context tab and in the translation area.
- _tags, to define tag-keywords that can help the localization team organize their work better over phrases. To add multiple tags use a comma-separator. Tags are visible in the editor's context tab. Read more about tags.
- _key, to define a custom string key instead of an auto-generated one based on source phrase.
Learn more on how metadata can improve the localization process by reading about character limits, developer comments and tags in Transifex documentation.
Note
Defining context makes it possible to distinguish between two identical source strings and disambiguate the translation.
Metadata examples
t('Contact us', {
_context: 'Support page CTA',
_tags: 'important,footer',
});
t('A string', {
_comment: 'A comment to the translators',
_charlimit: 30,
_tags: 't1,t2',
});
Escaping translations
Using the translation as is from the t
function inside HTML is dangerous for XSS attacks. The translation must be escaped based on two scenarios.
Escaping text translations
Escape the entire phrase using the escape
function.
import { t, escape } from '@transifex/native';
const translation = escape(t('Hello {username}', { username }));
// translation is safe to include in HTML
Escaping HTML source
HTML source content cannot be globally escaped. In that case, we can just escape the ICU variables using the _escapeVars
parameter.
const html = t('<b>Hello {username}</b>', {
username: username,
_escapeVars: true,
});
Updated almost 2 years ago