Pluralization
Pluralization is a vital feature in internationalization frameworks, enabling applications to correctly handle singular and plural forms based on numerical values. Vay simplifies pluralization, ensuring your translations adapt seamlessly to different quantities.
Understanding Pluralization
Pluralization in Vay involves defining different phrase variants for various numerical contexts. It allows your application to display the appropriate translation based on the quantity of items or subjects.
Defining Pluralized Phrases
To accommodate pluralization, define your phrases with options for different quantities. Vay supports defining these variants directly within your dictionaries. To pluralize, define a phrase that has numerical keys. These keys will later be matched to the quantity passed.
import { createProvider, defineDictionary, defineConfig } from '@vayjs/vay';
export const i18n = createProvider(
defineConfig({ defaultLocale: 'en' }),
// Add a simple dictionary with a interpolated phrase
defineDictionary('en', {
people: {
0: 'There are no users available',
1: 'There is a user available',
2: 'There are multiple users available',
10: 'There are lots of users available',
},
}),
);
// Reassign and export the translate function to make it easier to use
export const t = i18n.translate;
Utilizing Pluralization in Translations
When calling the translate function, pass the quantity in the TData
object using the count
key. Vay will automatically select the appropriate phrase variant based on this value. When no count
is passed, it defaults to zero.
// Import the created translation function
import { t } from './i18n.provider.ts';
// Outputs: 'There are no users available'
console.log(t('people.[...]', { count: 0 }));
// Outputs: 'There is a user available'
console.log(t('people.[...]', { count: 1 }));
// Outputs: 'There are multiple users available'
console.log(t('people.[...]', { count: 2 }));
// Outputs: 'There are multiple users available'
console.log(t('people.[...]', { count: 5 }));
// Outputs: 'There are lots of users available'
console.log(t('people.[...]', { count: 10 }));
TIP
The token
explicitly marks numerical phrases using the [...]
syntax.
INFO
The count property will try to match the closest lower or exact index, if available.
Tips for Effective Pluralization
- Locale-Specific Rules: Be mindful of locale-specific pluralization rules. Different languages have different rules for plural forms, and your dictionary definitions should account for these variations.
- Interpolation Usage: Utilize interpolation within your pluralizable phrases to insert the quantity directly into the translation, enhancing clarity and readability.
- Testing Across Locales: Test your pluralized phrases across all supported locales to ensure accuracy and appropriateness of translations.