Skip to content

Interpolation

Interpolation is a important concept in any i18n Framework, and is made as easy as possible in Vay. There are two different ways to handle interpolation, using the standard textual interpolation or the context bases interpolation. This page will show you how to perform textual interpolation, while the context page will go into detail on how to do contextual interpolation.

Adding interpolation to a Phrase

Textual interpolation in Vay allows for the insertion of dynamic values into translations. To denote a variable within a phrase, use double curly braces { { variableName } }. The variable will be replaced by a corresponding value provided in the translation call.

ts
import { createProvider, defineDictionary, defineConfig } from '@vayjs/vay';

export const i18n = createProvider(
    defineConfig({ defaultLocale: 'en' }),
    // Add a simple dictionary with a interpolated phrase
    defineDictionary('en', {
        greeting: 'Hello {{ name }}',
    }),
);

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

Providing Data for Interpolation

To interpolate content, pass an object with matching keys to the translate function. Each key's value replaces its corresponding placeholder in the phrase.

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

console.log(t('greeting', { name: 'World' })); // Outputs: 'Hello World'
console.log(t('greeting', { name: 'There' })); // Outputs: 'Hello There'

Usage Tips

  • Consistent Placeholder Names: Ensure the placeholder names in your phrases match the keys in the data object passed to the translate function.
  • Reuse and Readability: Design your phrases for reuse across different contexts, and choose clear, descriptive placeholder names for readability.

Textual interpolation is a powerful tool for making your translations dynamic and adaptable. By leveraging this feature, you can create more engaging and personalized content for users across different locales. Explore context-based interpolation on the context page for even more flexibility in handling translations.

Released under the MIT License.