Skip to content

Translating

Translating a token to the corresponding Phrase is the core mechanism of Vay. To translate a token, use the translate method of a VayProvider created previously.

INFO

Not sure how a VayProvider is created? Take a look at the Getting Started section.

Using the translate function

ts
// Import the created translation function
import { t } from './i18n.provider.ts';

console.log(t('start')); // Outputs: 'Phrase'
console.log(t('going.down')); // Outputs: 'A Level'
console.log(t('deeply.nested.phrase')); // Outputs: 'Are also possible'
ts
import { createProvider, defineDictionary, defineConfig } from '@vayjs/vay';

export const i18n = createProvider(
    defineConfig({ defaultLocale: 'en' }),
    // Add a simple dictionary with textual phrases
    defineDictionary('en', {
        start: 'Phrase',
        going: {
            down: 'A Level',
        },
        deeply: {
            nested: {
                phrases: 'Are also possible',
            },
        },
    }),
);

// Reassign and export the translate function to make it easier to use
export const t = i18n.translate;

The translate function also accepts additional translation data (which we will ignore for now) and the ability to override the language currently set on the translation provider, by providing a locale to the function directly.

ts
console.log(t('token', undefined, 'en')); // Outputs the token in English
console.log(t('token', undefined, 'es')); // Outputs the token in Spanish

API

The translate method is used to access a phrase from a provided token.

Type:

translate<Token extends PropertyPath<Phrases>>(token: Token, tData: TData | undefined, locale?: ISO639Code): string

Template:

  • Token: (Type: PropertyPath<Phrases>): The token used to identify the correct phrase.

Parameters:

  • token: (Type: PropertyPath<Phrases>): The token used to identify the correct phrase.
  • [tData]: (Type: Record<PropertyKey, unknown>): Additional data that can be passed to the function to configure interpolation, context as well as pluralization.
  • [locale]: (Type: ISO639Code): A optional locale to override the provider's locale.

Returns:

A string if a match was found, the token itself if no match was found or if there was an error during translation.

Released under the MIT License.