Skip to content

Instantly share code, notes, and snippets.

@Sebobo
Created April 7, 2020 10:28
Show Gist options
  • Save Sebobo/308afba352d1c7db2902f3103944fed1 to your computer and use it in GitHub Desktop.
Save Sebobo/308afba352d1c7db2902f3103944fed1 to your computer and use it in GitHub Desktop.
NeosCMS Eel helper to load a file with translations for the current locale as array. This allows for example to use the localisation features of the framework and forward all labels to a frontend app.
prototype(MyVendor.Package:Component.Example) < prototype(Neos.Fusion:Component) {
translations = ${MyVendor.Package.Translation.getTranslations('MyVendor.Package', 'MyJsApp')}
renderer = afx`
<div data-translations={Json.stringify(props.translations)} id="my-cool-app">Loading the app ...</div>
`
}
Neos:
Fusion:
defaultContext:
MyVendor.Package.Translation: MyVendor\Package\Eel\Helper\TranslationHelper
<?php
declare(strict_types=1);
namespace MyVendor\Package\Eel\Helper;
use Neos\Flow\Annotations as Flow;
use Neos\Eel\ProtectedContextAwareInterface;
use Neos\Flow\I18n\Locale;
use Neos\Flow\I18n\Service as I18nService;
use Neos\Flow\I18n\Xliff\Service\XliffFileProvider;
/**
* Translation helper for eel contexts
*/
class TranslationHelper implements ProtectedContextAwareInterface
{
/**
* @Flow\Inject
* @var XliffFileProvider
*/
protected $xliffFileProvider;
/**
* @Flow\Inject
* @var I18nService
*/
protected $i18nService;
/**
* @param string $packageKey
* @param string $sourceName
* @param Locale $locale
* @return array
*/
public function getTranslations(string $packageKey, string $sourceName, Locale $locale = null): array {
$fileId = $packageKey . ':' . $sourceName;
if (!$locale) {
$locale = $this->i18nService->getConfiguration()->getCurrentLocale();
}
$file = $this->xliffFileProvider->getFile($fileId, $locale);
$labels = [];
foreach ($file->getTranslationUnits() as $key => $value) {
$valueToStore = !empty($value[0]['target']) ? $value[0]['target'] : $value[0]['source'];
$labels[$key] = $valueToStore;
}
return $labels;
}
/**
* @param string $methodName
* @return bool
*/
public function allowsCallOfMethod($methodName): bool
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment