Custom Translator Functions
Define a custom translation function to use a different translation service or implement your own translation logic. This allows you to integrate any translation API or service that suits your needs, cache translations, or apply custom translation rules.
Translator Callback
To use a custom translation service, you can define a translateFn
in your plugin configuration. This function should accept the text to be translated, the target language code, and optionally the source language code. It should return the translated text as a string.
return [
'johannschopplich.content-translator' => [
'translateFn' => function (string $text, string $toLanguageCode, string|null $fromLanguageCode = null): string {
// Implement your custom translation logic here
return myCustomTranslateFunction($text, $toLanguageCode, $fromLanguageCode);
}
]
];
Custom Target Language with DeepL
In certain cases, a language code defined in Kirby might not match the language code expected by the translation service.
For example, you may have defined en
as a language code in your Kirby installation, but you want to translate to either British English (en-GB
) or American English (en-US
). DeepL recommends to specify the target English variant to improve the translation quality:
EN
- English (unspecified variant for backward compatibility; please selectEN-GB
orEN-US
instead)
LC_ALL
locale (if available). However, this will only work if the resulting language code is supported by DeepL.For your example, if you set your LC_ALL
locale to en_GB
, then DeepL will receive EN-GB
as the target language.For all other cases, use the custom translator function to map language codes on the fly:
use JohannSchopplich\ContentTranslator\DeepL;
return [
'johannschopplich.content-translator' => [
'translateFn' => function (string $text, string $toLanguageCode, string|null $fromLanguageCode = null): string {
// Translate all English content to British English
if ($toLanguageCode === 'en') {
$toLanguageCode = 'en-gb';
}
$deepL = new DeepL();
return $deepL->translate($text, $toLanguageCode, $fromLanguageCode);
}
]
];