开源软件名称(OpenSource Name):martinandert/counterpart开源软件地址(OpenSource Url):https://github.com/martinandert/counterpart开源编程语言(OpenSource Language):JavaScript 99.6%开源软件介绍(OpenSource Introduction):CounterpartA translation and localization library for Node.js and the browser. The project is inspired by Ruby's famous I18n gem. Features:
InstallationInstall via npm: % npm install counterpart UsageRequire the counterpart module to get a reference to the var translate = require('counterpart'); This function expects a LookupTranslation data is organized as a nested object using the top-level key as namespace. E.g., the damals package ships with the translation: {
damals: {
about_x_hours_ago: {
one: 'about one hour ago',
other: 'about %(count)s hours ago'
}
/* ... */
}
} Translations can be looked up at any level of this object using the translate('damals') // => { about_x_hours_ago: { one: '...', other: '...' } } The translate('damals.about_x_hours_ago.one') // => 'about one hour ago'
translate(['damals', 'about_x_hours_ago', 'one']) // => 'about one hour ago'
translate(['damals', 'about_x_hours_ago.one']) // => 'about one hour ago' The translate('damals.about_x_hours_ago.one')
translate('about_x_hours_ago.one', { scope: 'damals' })
translate('one', { scope: 'damals.about_x_hours_ago' })
translate('one', { scope: ['damals', 'about_x_hours_ago'] }) The translate('damals.about_x_hours_ago.one', { separator: '*' })
// => 'missing translation: en*damals.about_x_hours_ago.one' Since we changed what our key should be split by counterpart will be looking for the following object structure: {
'damals.about_x_hours_ago.one': 'about one hour ago'
} The translate.setSeparator('*') // => '.' (returns the previous separator) There is also a InterpolationTranslations can contain interpolation variables which will be replaced by values passed to the function as part of the options object, with the keys matching the interpolation variable names. E.g., with a translation translate('foo', { bar: 'baz' }) // => 'foo baz' PluralizationTranslation data can contain pluralized translations. Pluralized translations are provided as a sub-object to the translation key containing the keys {
x_items: {
zero: 'No items.',
one: 'One item.',
other: '%(count)s items.'
}
} Then use the translate('x_items', { count: 0 }) // => 'No items.'
translate('x_items', { count: 1 }) // => 'One item.'
translate('x_items', { count: 42 }) // => '42 items.' The name of the option to select a pluralization is always Note that this library currently only supports an algorithm for English-like pluralization rules (see locales/en.js. You can easily add pluralization algorithms for other locales by adding custom translation data to the "counterpart" namespace. Pull requests are welcome. As seen above, the FallbacksIf for a key no translation could be found, To mitigate this, provide the translate('baz', { fallback: 'default' }) Dealing with missing translationsWhen a translation key cannot be resolved to a translation, regardless of whether a fallback is provided or not, translate.onTranslationNotFound(function(locale, key, fallback, scope) {
// do important stuff here...
}); Use As stated in the Fallbacks section, if for a key no translation could be found, You can customize this output by providing your own missing entry generator function: translate.setMissingEntryGenerator(function(key) {
// console.error('Missing translation: ' + key);
return 'OMG! No translation available for ' + key;
}); LocalesThe default locale is English ("en"). To change this, call the translate.getLocale() // => 'en'
translate.setLocale('de') // => 'en' (returns the previous locale)
translate.getLocale() // => 'de' Note that it is advised to call In case of a locale change, the translate.onLocaleChange(function(newLocale, oldLocale) {
// do important stuff here...
}, [callbackContext]); Use You can temporarily change the current locale with the translate.withLocale(otherLocale, myCallback, [myCallbackContext]);
Another way to temporarily change the current locale is by using the translate('foo', { locale: 'de' }); There are also Fallback LocalesYou can provide entire fallback locales as alternatives to hard-coded fallbacks. translate('baz', { fallbackLocale: 'en' }); Fallback locales can also contain multiple potential fallbacks. These will be tried sequentially until a key returns a successful value, or the fallback locales have been exhausted. translate('baz', { fallbackLocale: [ 'foo', 'bar', 'default' ] }) Globally, fallback locales can be set via the translate.setFallbackLocale('en')
translate.setFallbackLocale([ 'bar', 'en' ]) // Can also take multiple fallback locales Adding Translation DataYou can use the translate.registerTranslations('de', require('counterpart/locales/de'));
translate.registerTranslations('de', require('./locales/de.json')); The data object to merge should contain a namespace (e.g. the name of your app/library) as top-level key. The namespace ensures that there are no merging conflicts between different projects. Example (./locales/de.json): {
"my_project": {
"greeting": "Hallo, %(name)s!",
"x_items": {
"one": "1 Stück",
"other": "%(count)s Stücke"
}
}
} The translations are instantly made available: translate('greeting', { scope: 'my_project', name: 'Martin' }) // => 'Hallo, Martin!' Note that library authors should preload their translations only for the default ("en") locale, since tools like webpack or browserify will recursively bundle up all the required modules of a library into a single file. This will include even unneeded translations and so unnecessarily bloat the bundle. Instead, you as a library author should advise end-users to on-demand-load translations for other locales provided by your package: // Execute this code to load the 'de' translations:
require('counterpart').registerTranslations('de', require('my_package/locales/de')); Registering Default InterpolationsSince v0.11, Counterpart allows you to register default interpolations using the translate.registerTranslations('en', {
my_namespace: {
greeting: 'Welcome to %(app_name)s, %(visitor)s!'
}
});
translate.registerInterpolations({ app_name: 'My Cool App' });
translate('my_namespace.greeting', { visitor: 'Martin' })
// => 'Welcome to My Cool App, Martin!'
translate('my_namespace.greeting', { visitor: 'Martin', app_name: 'The Foo App' })
// => 'Welcome to The Foo App, Martin!' As you can see in the last line of the example, interpolations you give as options to the Using a key transformerSometimes it is necessary to adjust the given translation key before the actual translation is made, e.g. when keys are passed in mixed case and you expect them to be all lower case. Use translate.setKeyTransformer(function(key, options) {
return key.toLowerCase();
}); Counterpart's built-in key transformer just returns the given key argument. LocalizationThe counterpart package comes with support for localizing JavaScript Date objects. The var date = new Date('Fri Feb 21 2014 13:46:24 GMT+0100 (CET)');
translate.localize(date) // => 'Fri, 21 Feb 2014 13:46'
translate.localize(date, { format: 'short' }) // => '21 Feb 13:46'
translate.localize(date, { format: 'long' }) // => 'Friday, February 21st, 2014 13:46:24 +01:00'
translate.localize(date, { type: 'date' }) // => 'Fri, 21 Feb 2014'
translate.localize(date, { type: 'date', format: 'short' }) // => 'Feb 21'
translate.localize(date, { type: 'date', format: 'long' }) // => 'Friday, February 21st, 2014'
translate.localize(date, { type: 'time' }) // => '13:46'
translate.localize(date, { type: 'time', format: 'short' }) // => '13:46'
translate.localize(date, { type: 'time', format: 'long' }) // => '13:46:24 +01:00'
translate.registerTranslations('de', require('counterpart/locales/de'));
translate.localize(date, { locale: 'de' }) // => 'Fr, 21. Feb 2014, 13:46 Uhr' Sure, you can integrate custom localizations by adding to or overwriting the "counterpart" namespace. See locales/en.js and locales/de.js for example localization files. As an instanceYou can invoke an instance of Counterpart should you need various locales displayed at once in your application: var Counterpart = require('counterpart').Instance;
var instance = new Counterpart();
instance.registerTranslations('en', { foo: 'bar' });
instance.translate('foo'); Error handlingWhen a translation fails, translate.onError(function(err, entry, values) {
// do some error handling here...
}); Use ContributingHere's a quick guide:
LicenseReleased under The MIT License. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论