@rollin
To pass Symfony translated sentences to Twig, follow these steps:
- Install the Translation component if you haven't already:
1
|
composer require symfony/translation
|
- Configure the Translation component in your config/packages/translation.yaml file:
1
2
3
4
5
6
7
|
framework:
default_locale: en
translator:
paths:
- '%kernel.project_dir%/translations'
fallbacks:
- en
|
- Create a translations file under translations directory. For example, create messages.en.yaml to store English translations:
- In your Symfony controller, use the trans() function to translate sentences and pass them to Twig:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentTranslationTranslatorInterface;
class YourController
{
public function index(TranslatorInterface $translator): Response
{
$translatedSentence = $translator->trans('hello');
return $this->render('your_template.html.twig', [
'translatedSentence' => $translatedSentence,
]);
}
}
|
- In your Twig template (your_template.html.twig), output the translated sentence:
1
|
{{ translatedSentence }}
|
When the template is rendered, the translated sentence will be displayed based on the current locale configuration. You can add more translations to the messages.en.yaml
file or create additional translation files for different languages.