May be someone will need my solution because I think it is boring to write
{{ message|trans(arguments = [], domain = null, locale = null) }}
For every translation.
First, I have created a service to check if the translation for a given locale is available :
use Symfony\Component\HttpKernel\KernelInterface;
class LocaleChecker
{
const TRANSLATE_FILE_PATTERN = 'mail.%s.yml';
/**
* @var KernelInterface
*/
private $storage;
public function __construct(KernelInterface $kernel)
{
$this->storage = $kernel;
}
/**
* @param string $locale
*
* @return bool
*/
public function isLocaleExist(string $locale)
{
$filename = sprintf(self::TRANSLATE_FILE_PATTERN, $locale);
$path = sprintf('%s%s', $this->storage->getTranslationsDir(), $filename);
return file_exists($path);
}
}
Then I have created a twig extension to do the job for me :
<?
use FrontBundle\Service\Translate\LocaleChecker;
use Symfony\Component\Translation\TranslatorInterface;
class FallbackEnglishExtension extends \Twig_Extension
{
/**
* @var LocaleChecker
*/
private $localeChecker;
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct(LocaleChecker $localeChecker, TranslatorInterface $translator)
{
$this->localeChecker = $localeChecker;
$this->translator = $translator;
}
public function getFilters()
{
return [
new \Twig_Filter('trans_mail', [$this, 'translate']),
];
}
/**
* @param string $translateKey
* @param string $locale
*
* @return string
*/
public function translate(string $translateKey, string $locale = 'en_EN')
{
if ($this->localeChecker->isLocaleExist($locale)) {
return $this->translator->trans($translateKey, [], 'mail', $locale);
}
return $this->translator->trans($translateKey, [], 'mail', $locale);
}
}