Nextcloud L10n helpers for apps and libraries.
npm i -S @nextcloud/l10n
Apps normally use the Nextcloud provided translation mechanism which allows to translate backend (PHP) strings together with the frontend. This can either be done using the Nextcloud Transifex automatization or translations can be done manually. See the localization docs for how to setup.
When using the Nextcloud translation system (manually or with automated Transifex) Nextcloud will automatically register the translations on the frontend. In this case all you have to do is to import the translation functions from this package like shown below:
import { t, n } from '@nextcloud/l10n'
// Or
import { translate as t, translatePlural as n } from '@nextcloud/l10n'
Note
In order to not break the l10n string extraction scripts, make sure to use the aliases t
and n
.
t('myapp', 'Hello!')
t('myapp', 'Hello {name}!', { name: 'Jane' })
By default placeholders are sanitized and escaped to prevent XSS. But you can disable this behavior if you trust the user input:
t(
'myapp',
'See also the {linkStart}documentation{linkEnd}.',
{
linkStart: '<a href="http://example.com">'
linkEnd: '</a>',
},
undefined, // this would be a number replacement
{ escape: false },
)
n('myapp', '%n cloud', '%n clouds', 100)
Of course also placeholders are possible:
n('myapp', '{name} owns %n file', '{name} owns %n files', 100, { name: 'Jane' })
It is also possible to use this package for Nextcloud independent translations. This is mostly useful for libraries that provide translated strings.
Independent means you can use this without Nextcloud registered translations buy just providing your .po
files.
If you decide to use this way you have to extract the translation strings manually, for example using the gettext-extractor.
import { getGettextBuilder } from '@nextcloud/l10n/gettext'
const po = ... // Use https://github.com/smhg/gettext-parser to read and convert your .po(t) file
// When using this for a Nextcloud app you can auto-detect the language
const gt = getGettextBuilder()
.detectLocale()
.addTranslation('sv', po)
.build()
// But it is also possible to force a language
const gt = getGettextBuilder()
.setLocale('sv')
.addTranslation('sv', po)
.build()
To make things easier you could also create aliases for this in a module and reuse it in your code:
// When using JavaScript
export const t = (...args) => gt.gettext(...args)
export const n = (...args) => gt.ngettext(...args)
// When using Typescript
export const t = (...args: Parameters<typeof gt.gettext>) => gt.gettext(...args)
export const n = (...args: Parameters<typeof gt.ngettext>) => gt.ngettext(...args)
gt.gettext('my source string')
// or if you are using the aliases mentioned above:
t('my source string')
gt.gettext('this is a {placeholder}. and this is {key2}', {
placeholder: 'test',
key2: 'also a test',
})
gt.ngettext('%n Mississippi', '%n Mississippi', 3)
// or if you are using the aliases mentioned above:
n('%n Mississippi', '%n Mississippi', 3)